File Logging using NLog Windows Form Application in .NET Core
Today in this article, we will see how to achieve File-based logging in Windows Forms Application using .NET Core application.
As we know .NET Core has introduced ILogger as a generic interface for logging purposes. This framework supported interface ILogger can be used across different types of applications like ASP.NET Core API logging, Console App logging or Windows Form app logging using built-in providers.
Today in this article, we will cover below aspects,
We also discovered that the File-based logging provider is still not available through the .NET Core framework and we need to rely on external solutions.
Microsoft recommends using a third-party logger framework like a Serilog or NLog for other high-end logging requirements like Database or File/Rolling File logging.
Implement DI in Windows Forms
Before we start adding NLog logging in the Windows forms app, we need to understand how to add DI framework in Windows Forms.
As we know , unlike ASP.NET Core the Windows Forms app doesn’t have dependency injection built into the framework but using few approaches like as discussed in the article Using Service provider for DI in Windows Forms App or using Generic HostBuilder for DI in Windows Forms App we can very much achieve the same.
Getting started
Here I am using a Forms/Windows .NET Core 3.1 application.
Please add below Nuget Packages.
PM> Install-Package NLog.Extensions.Logging
PM> Install-Package Microsoft.Extensions.Hosting
DI Container
Please create Generic HosBuilder and register the dependencies that need to injected. These changes can be done in the Main() method.
Class HosBuilder is available through a namespace Microsoft.Extensions.Hosting
I have added my custom BusinessLayer and DataAccessLayer objects below and registered in the container.
var builder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddScoped<Form1>();
services.AddScoped<IBusinessLayer, BusinessLayer>();
services.AddSingleton<IDataAccessLayer, CDataAccessLayer>();
});
NLog Configuration
NLog configuration can be enabled as below,
services.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
Here nlog.cofig file contains the log properties and configuration for the logging file.
Sample nlog.config 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="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>
Here code can be added in the Main() methods as below ,
///Generate Host Builder and Register the Services for DI
var builder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddScoped<Form1>();
services.AddScoped<IBusinessLayer, BusinessLayer>();
services.AddSingleton<IDataAccessLayer, CDataAccessLayer>();
services.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
});
var host = builder.Build();
using (var serviceScope = host.Services.CreateScope())
{
var services = serviceScope.ServiceProvider;
try
{
var form1 = services.GetRequiredService<Form1>();
Application.Run(form1);
Console.WriteLine("Success");
}
catch (Exception ex)
{
Console.WriteLine("Error Occured");
}
}
Implementation for class ‘Form1’ with DI of Logger and business objects as below.
Let’s run the application and check the log details captured in a file.
That’s all! Happy Coding.
Summary
File logging provider is not yet available through the .NET Core framework. However, NLog helps us enabling logging in a few simple steps and addresses the file-logging requirement easily in .NET Core based Desktop or Windows Forms application.
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.
Please share this article with your friends and subscribe to the blog to get a notification on freshly published best practices of software development.