How To Use NLog With ASP.NET Core Application

How To Use NLog With ASP.NET Core Application

Introduction


Logging is the heart of an application. It is very important for debugging and troubleshooting, as well as, for smoothness of the application.

With the help of logging, we can have end-to-end visibility for on-premise systems, to only give a fraction of that visibility for cloud-based systems. It can be difficult to instrument the cloud and, thus, alternative approaches like logging, are required to give visibility into cloud-based components which otherwise can become black boxes from a performance or system monitoring perspective.

Install NuGet Package For Nlog


To use Nlog logging, you need to first add the Nlog plugin. For adding the plugin, you use these two different ways.
  1. NuGet Package Manager.
  2. NuGet command.

You can find the Nuget command for Nlog on the mentioned link - Click Here

 

Create and add Nlog config file


We need to create the Nlog.config file at the root of the project where we can keep the Nlog related configuration.

Example
  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.       autoReload="false"  
  5.       throwConfigExceptions="true"  
  6.       internalLogLevel="Off"  
  7.       internalLogFile="c:\temp\internal-nlog.txt">  
  8.         
  9. <targets>  
  10.     <!-- write logs to file  -->  
  11.     <target name="file" xsi:type="File"  layout="                
  12.              -----------Time Stamp: ${longdate}----------                 
  13.              Log Level: ${level}${newline}                           
  14.              Logger Name : ${logger}${newline}                
  15.              Log Message : ${message}${newline}                
  16.              Exception Message: ${event-context:item=ErrorMessage}${newline}    
  17.              Browser Detail:  ${event-context:item=BrowserDetail}${newline}    
  18.              Session Id: ${event-context:item=SessionId}               
  19.              fileName="${basedir}/logs/${shortdate}.log" />  
  20. </targets>  
  21.   
  22. <rules>  
  23.     <logger name="*" minlevel="Error" writeTo="file" enabled="true" />  
  24.     <logger name="*" minlevel="Trace" writeTo="database" enabled="true"/>  
  25.     <logger name="Microsoft.*" maxlevel="Info" final="true" />  
  26.   </rules>  
  27. </nlog>  

For more details, please click on the mentioned link - Click Here

 

Update Startup file


We need to load the Nlog related configuration in the relvent startup file. Please refer the below code.
  1. NLog.GlobalDiagnosticsContext.Set("defaultConnection", Connection string);  
  2. NLog.LogManager.LoadConfiguration(env.ContentRootPath + "\\NLog.config");  

Custom Nlog Manager

Manager Class

  1. public static class NLogManager {  
  2.   
  3.     public static ILogger _logger = NLog.LogManager.GetCurrentClassLogger();  
  4.   
  5.     public static void InfoLog(NLogData nLogData) {  
  6.     LogEventInfo theEvent = new LogEventInfo(LogLevel.Info, NLogManager._logger.Name, nLogData.Message);  
  7.     SetLogEventInfo(theEvent, nLogData);  
  8.     _logger.Log(theEvent);  
  9.     }  
  10.   
  11.     public static void DebugLog(NLogData nLogData) {  
  12.     LogEventInfo theEvent = new LogEventInfo(LogLevel.Debug, NLogManager._logger.Name, nLogData.Message);  
  13.     SetLogEventInfo(theEvent, nLogData);  
  14.     _logger.Log(theEvent);  
  15.     }  
  16.   
  17.     public static void ErrorLog(NLogData nLogData) {  
  18.     LogEventInfo theEvent = new LogEventInfo(LogLevel.Error, NLogManager._logger.Name, nLogData.Message);  
  19.     SetLogEventInfo(theEvent, nLogData);  
  20.     _logger.Log(theEvent);  
  21.     }  
  22. }  

Custom Event parameter for logging

  1. private static void SetLogEventInfo(LogEventInfo theEvent, NLogData nLogData) {  
  2.    theEvent.Properties["SessionId"] = nLogData.SessionId;  
  3.    theEvent.Properties["BrowserDetail"] = nLogData.BrowserDetail;  
  4. }  

If you need to log more parameters into the database, just add a property in the above method and the same adds into Nlog.config file.

Model for NLog logging

  1. public class NLogData {  
  2.    public string SessionId {get;set;}  
  3.    public string BrowserDetail {get;set;}  
  4. }