Introduction To NLog With ASP.NET Core

Logging is a very critical and essential part of any software. It helps us in the investigation of the essence of problems. ASP.NET Core has built-in support for logging APIs and is able to work with various logging providers. Using these built-in providers, we can send application logs to one or more destinations and also, we can plug in third-party logging frameworks such as Serilog, Nlog, etc. In this article, we learn how to implement NLog with ASP.NET Core.

Introduction
 
Logging is a very critical and essential part of any software. It helps us in the investigation of the essence of problems. ASP.NET Core has built-in support for logging APIs and is able to work with various logging providers. Using these built-in providers, we can send application logs to one or more destinations and also, we can plug in third-party logging frameworks, such as Serilog, Nlog, etc. In this article, we learn how to implement NLog with ASP.NET Core.
 
NLog is an open source and flexible framework that works with various .NET platforms including .NET Standard, Full framework (i.e., .NET Framework 4.7), Xamarin (Android and iOS), Windows phone, and UWP. NLog is easy to use and extend. Also, it provides more flexibility in term of configuration. We can also change the logging configuration on-the-fly. The target is used to store, display, and pass the log messages to the provided destination. NLog can write a log to one or more targets at the same time. NLog provides more than 30 targets that include file, event log, database, email, console, etc.
 
Following are the steps to configure NLog in ASP.NET Core application.
 
Step 1 - Add NLog dependency either manually to csproj file or using NuGet
 
We can add an NLog dependency using NuGet by executing the following commands.
  1. PM> Install-Package NLog  
  2. PM> Install-Package NLog.Web.AspNetCore  
 The above two commands are used to add dependencies to the csproj file.
  1. <ItemGroup>  
  2.   <PackageReference Include="Microsoft.AspNetCore.App" />  
  3.   <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />  
  4.   <PackageReference Include="NLog.Web.AspNetCore" Version="4.5.4" />  
  5.   <PackageReference Include="NLog" Version="4.5.4" />  
  6. </ItemGroup>  
Step 2 - Create nlog configuration file
 
The NLog configuration file is an XML file that contains the settings related to NLog. This file must be named in lower-case and may be put in the root of our project.
 
There are two main elements required by every configuration: targets and rules. It may also have other elements - such as extensions, include, and variables. These, however, are optional and can be useful in advanced scenarios.
 
The targets element defines a log target that is defined by a target element. There are two main attributes: name (name of the target) and type (target type such as - file, database, etc.). There are also additional attributes available with the target element but those depend on the target type; for example - target type is a file, we need to define the filename parameter that is used to define the output file name. Apart from this, the target element contains the layout attribute also that defines the logging data format.
 
The rules element maps the target with log level. It has logger element that contains this mapping. The logger element has following attributes.
  • name – name of logger pattern
  • minlevel – minimal log level
  • maxlevel – maximum log level
  • level – single log level
  • levels - comma separated list of log levels
  • writeTo – comma separated list of targets to write to
  • final – no rules are processed after a final rule matches
  • enabled - set to false to disable the rule without deleting it
Example
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" internalLogLevel="info" internalLogFile="internalLog.txt">  
  3.     <extensions>  
  4.         <add assembly="NLog.Web.AspNetCore" />  
  5.     </extensions>  
  6.     <!-- the targets to write to -->  
  7.     <targets>  
  8.         <!-- write to file -->  
  9.         <target xsi:type="File" name="alldata" fileName="demo-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />  
  10.         <!-- another file log. Uses some ASP.NET core renderers -->  
  11.         <target xsi:type="File" name="otherFile-web" fileName="demo-Other-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />  
  12.     </targets>  
  13.     <!-- rules to map from logger name to target -->  
  14.     <rules>  
  15.         <logger name="*" minlevel="Trace" writeTo="alldata" />  
  16.         <!--Skip non-critical Microsoft logs and so log only own logs-->  
  17.         <logger name="Microsoft.*" maxLevel="Info" final="true" />  
  18.         <loggername="*"minlevel="Trace"writeTo="otherFile-web" />  
  19.     </rules>  
  20. </nlog> 
This file must be available at a place where project's dll is placed. So, we need to enable the "copy to bin" folder.
 
 
 
Step 3 - Configure NLog in application
 
Using "UseNLog" method, we can add NLog in a request pipeline as a dependency. To catch an error in program class, we can set up a logger class and after initialization of program class, we can safely shut down the log manager.
  1. public class Program  
  2. {  
  3.     public static void Main(string[] args)  
  4.     {  
  5.         var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();  
  6.         try  
  7.         {  
  8.             logger.Debug("init main function");  
  9.             CreateWebHostBuilder(args).Build().Run();  
  10.         }  
  11.         catch (Exception ex)  
  12.         {  
  13.             logger.Error(ex, "Error in init");  
  14.             throw;  
  15.         }  
  16.         finally  
  17.         {  
  18.             NLog.LogManager.Shutdown();  
  19.         }  
  20.               
  21.     }  
  22.   
  23.     public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>  
  24.         WebHost.CreateDefaultBuilder(args)  
  25.             .UseStartup<Startup>()  
  26.             .ConfigureLogging(logging =>  
  27.             {  
  28.                 logging.ClearProviders();  
  29.                 logging.SetMinimumLevel(LogLevel.Information);  
  30.             })  
  31.             .UseNLog();  
  32. }  
In the above code, we are also configure the logging (i.e. SetMinimumLevel). This can be overriden by the appsettings.json file. So, we need to adjust it correctly as we need.
 
Demo
 
As we know, Logger is available as DI (dependency injection) to every controller by default, we get an ILogger object in the constructor of the controller class.
  1. public class HomeController : Controller  
  2. {  
  3.     private readonly ILogger<HomeController> _logger;  
  4.   
  5.     public HomeController(ILogger<HomeController> logger)  
  6.     {  
  7.         _logger = logger;  
  8.     }  
  9.     public IActionResult Index()  
  10.     {  
  11.         _logger.LogInformation("HomeController.Index method called!!!");  
  12.         return View();  
  13.     }  
  14. }  
Output
 
 
 
The file format can be defined using the layout attribute in a target element.
 
Summary
 
NLog is an open source framework for logging. It is easy to configure with ASP.NET Core application. In this article, I have explained about NLog - file logging configuration with ASP.NET Core 2.
 
You can view or download the source code from the GitHub link here.