Integrating NLog With ASP.NET Core Web Application

Introduction

 
In real world applications a proper error logging mechanism is essential to track and troubleshoot the unexpected behavior of the application. In Asp.Net Core we have a built in Logging API that is included in the Microsoft.Extensions.Logging which comes as a NuGet package.
 
With this API, we can log information to different built in logging providers like Console, Debug, EventListener, TraceListeners etc. To extend the number of providers Microsoft has also collaborated with various third party logging providers like NLog, Serilog, Loggr, Log4Net and some others.
 
In this article, we will explore Asp.Net Core integration with NLog, one of the most popular third party logging provider.
 

Integration Steps

 
In this article, we will be covering the NLog integration with an Asp.Net Core web application. There are three steps involved in this process. They are:
  • Adding NLog NuGet Package
  • Adding NLog Configuration
  • Adding NLog Provider

Adding NLog NuGet Package

 
As a first step we need to install NLog from NuGet package manager.
 
To do this, right click the Project from Solution Explorer and select Manage NuGet Packages from the context menu. It will open the Package Manager Solution window.
 
From the Package Manager window, browse for NLog.Web.AspNetCore NuGet package as shown in the below image.
 
Integrating NLog With ASP.NET Core Web Application
 
Next, select the latest stable version and click Install. At this point of time the latest version is 4.9.3. If a previous version is required, we can choose from version dropdown.
 
Integrating NLog With ASP.NET Core Web Application
 
This will install NLog NuGet package to our project. Once we get the success message we can move to the next step, i.e., adding NLog configuration.
 

Adding NLog Configuration

 
After installing NLog NuGet package we need to configure it. Configuration information for NLog will be kept inside a configuration file, namely nlog.config in the application root folder.
 
This nlog.config is not an auto generated one. So we need to add it manually.
 
To add nlog.config, right click the Project and select Add then New Item from context menu. From the new item template window, search for Text file.
 
Integrating NLog With ASP.NET Core Web Application
 
Name the text file nlog.config as shown in the below image.
 
Integrating NLog With ASP.NET Core Web Application
 
NLog configuration file is an XML based configuration file. Below is the minimum configuration required to write the log information to a file.
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"  
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  
  4.     <!-- the targets to write -->  
  5.     <targets>  
  6.         <!-- write to file -->  
  7.         <target name="applog" xsi:type="File"   
  8.         fileName="C:\Log\applog-${shortdate}.log"  
  9.         layout="${longdate} - ${message} -   
  10.         ${exception:format=StackTrace}${newline}" />  
  11.     </targets>  
  12.     <!-- rules to map from logger name to target -->  
  13.     <rules>  
  14.         <!-- all logs including Microsoft -->  
  15.         <logger name="*" minlevel="Trace" writeTo="applog" />  
  16.     </rules>  
  17. </nlog>  
As per the above configuration NLog will create log file with the name applog-{today’s date}.log in the path C:\Log\, if it does not already exist. You can also give any physical path as you require.
 
The logging rule enforces the minimum level of logging we need.
 
Here we are covering only a minimum configuration which will log application exceptions to a log file. To see more configuration options, please visit NLog Official Documentation in GitHub
 
At build time this configuration file should be copied to the Output directory. To get this done, right click the nlog.config file from the Solution Explorer and select “Properties”.
 
In the Properties window, under “Advanced” section, go to Copy to Output Directory property and choose Copy if Newer as value.
 
Integrating NLog With ASP.NET Core Web Application
 
Now that we have finished the configuration section we can move to the final step, Adding NLog Provider.
 

Adding NLog Provider

 
To add NLog as one of the logging providers we need to modify the CreateHostBuilder method in the Program.cs file. The below code snippet will enable NLog logging provider.
 
Integrating NLog With ASP.NET Core Web Application
  1. .ConfigureLogging((hostingContext, logging) => {                          
  2.      logging.AddNLog(hostingContext.Configuration.GetSection("Logging"));  
  3. });  
As you can see in the snippet, the logging levels will be applied based on the Loggingconfiguration provided in the appsettings.json file.
 
Below is the default logging configuration Visual Studio creates in appsettings.json file while creating new project. You can change this logging levels as per your requirement.
 
Integrating NLog With ASP.NET Core Web Application
 
For advanced logging level configuration, please visit Microsoct Official Page.
 
With this we have completed NLog integration with our Asp.Net Core Web application. Now let us test the NLog log provider by throwing an exception.
 

Testing NLog Provider

 
To test the NLog provider we are using Microsoft Logging API. As mentioned in the introduction section the API is included in Microsoft.Extensions.Logging package which is already added in Asp.Net Core Web application template.
 
The interface we are using to log errors is ILogger from Microsoft.Extensions.Logging namespace. ILogger is already available in the application’s dependency container because the WebHost builder is adding Logging service to dependency container along with other necessary services.
 
So we can inject the ILogger type through our HomeController constructor as shown in the below image.
 
Integrating NLog With ASP.NET Core Web Application
 
Next we have to generate an Exception in the Index action and log that to the ILogger object.
 
Integrating NLog With ASP.NET Core Web Application
 
Here we are creating a divided by zero exception and logging to our logger API. Next we can verify the log file.
 
Integrating NLog With ASP.NET Core Web Application
 
Log file is created and exception is logged as per the configuration parameters specified.
 

Summary

 
In this article we covered basic integration steps of NLog library with Asp.Net Core 3.1 web application. There are a few other third party logging providers which are also available as NuGet packages.