Using NLog File logging in WPF Application
Today in this article, we will see how to perform logging using NLog File logging in WPF (Windows Presentation Foundation) .NET Core application.
We shall be leveraging the DI( Dependency Injection) framework to DI the NLog logger object into the mini IoC Container in a .NET Core-based WPF application.
Today in this article, we will cover below aspects,
As we understood .NET Core only provides basic providers for logging purposes like Console, Debug, EventSource, etc.
File logging providers like File or RollingFile are still not available through the .NET Core framework.
Microsoft recommends using a third-party logger framework like a Serlilog or Log4Net or NLog for high-end logging requirements like Database or File/Rolling File logging.
So here we need to rely on external solutions and today we shall see how to use NLog addressing the logging requirement in the WPF(Windows Presentation Foundation) app.
We shall see File/RollingFile logging or Console logging types using NLog.
Getting Started
Here I am using a WPF App (.NET Core) application template.
Creating Generic HostBuilder
We will be leveraging the DI( Dependency Injection) framework to inject the NLog logger.
So as a first step, Let’s create a generic Hostbuilder. This HostBuilder shall help us to define our DI Container too.
Please install the NuGet package from the NuGet Package manager or PMC,
PM> Install-Package Microsoft.Extensions.Hosting -Version 3.1.1
The HostBuilder class is available from the following namespace,
using Microsoft.Extensions.Hosting;
Configuring NLog in WPF App
NLog can be installed from NuGet Packages Manager,
PM> Install-Package NLog.Web.AspNetCore -Version 4.9.1
OR
Please install the package through Nuget Package Manager,
Please create Generic HosBuilder and register your services and business dependencies. We shall also be registering the NLog interface.
I have created a WPF window called ‘EmployeeWindow‘ which can be registered as a singleton instance in the IoC container.
See below the implementation for HostBuilder and registration for NLog logging.
These changes can be done in the App() constructor,
host = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
//Lets Create single tone instance of Master windows
services.AddSingleton<EmployeeWindow>();
})
The next step is to register NLog in the IoC container using configure logging.
We can also set a minimum level of logging as default Example ‘Trace’ or ‘Information’ as below,
host = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
//Lets Create single tone instance of Master windows
services.AddSingleton<EmployeeWindow>();
}).ConfigureLogging(logBuilder =>
{
logBuilder.SetMinimumLevel(LogLevel.Information);
logBuilder.AddNLog("nlog.config");
}).Build();
Please add a new nLog.config file if not available using Visual Studio ->Add New Item.
This file needs to be updated with log layout details and configuration as given below as an example.
Below is the complete implementation for IoC container implementation which you need to add to the App() constructor method.
All set Let now define and do dependency injection of the ILogger instance within the Application Class as below,
public partial class EmployeeWindow : Window
{
private readonly ILogger _logger;
public EmployeeWindow(ILogger<EmployeeWindow> logger)
{
_logger = logger;
InitializeComponent();
}
..
}
The log file shall be created in the project output directory unless specified with a custom path.
Below is an example of file logging created by NLog,
NLog.Config File
Sample NLog.config file is as below,
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="Info">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!-- the targets to write to -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="allfile" fileName="nlog-thecodebuzz-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />
</rules>
</nlog>
</configuration>
References: Dependency Injection in WPF in .NET Core
Please let me know if you have any questions or suggestions. Please sound off your comments below.
Happy Coding !!
Summary
Logging in .NET Core is simplified. It is possible to address high-end logging requirements like File logging using NLog. NLog helps us enable logging in a few simple steps and addresses high-end logging requirements like file logging etc.
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.