Subscribe to Youtube channel

Implement Logging in CSV file using Nlog in .net core MVC application- part 2

In previous article "Implement Nlog in .Net core MVC application part 1"  I have demonstrated how we can implement basic setup of NLog in .core mvc application. In previous article we have logged the exceptions in flat file system. In this article I will show you how you can write the exception and custom logs in csv file. Writing logs in csv file can enable us better readability of logs in tabular form.

 


 

 

Lets start the implementation of it, I going to use the same example project used in previous demonstration.

Modify the Nlog.config file as follows, added new target and rule for logging logs in csv file.

 <?xml version="1.0" encoding="utf-8" ?>  
 <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"  
    autoReload="true"  
    throwExceptions="false"  
    internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">   
  <variable name="myvar" value="myvalue"/>  
   <targets>  
   <target xsi:type="File" name="logError" fileName="${basedir}/logs/${shortdate}.log"  
       layout="${longdate} ${uppercase:${level}} ${message}" />  
   <target xsi:type="File" name="logErrorWithCSV" fileName="${basedir}/logs/${shortdate}.csv">  
   <layout xsi:type="CsvLayout" delimiter="Pipe" withHeader="true">  
     <column name="Date" layout="${longdate}" />  
     <column name="level" layout="${level:upperCase=true}"/>  
     <column name="message" layout="${message}" />  
     <column name="exception" layout="${exception:format=ToString}"/>      
     <column name="stacktrace" layout="${stacktrace:topFrames=10}" />     
     <column name="CustomProperty" layout="${event-properties:CustomProperty}"/>  
   </layout>  
  </target>  
  </targets>  
  <rules>   
   <logger name="ErrorLogFile" minlevel="Debug" writeTo="logError" />  
   <logger name="logErrorWithCSV" minlevel="Debug" writeTo="logErrorWithCSV" />  
  </rules>  
 </nlog>  

 

Modify the IloggerManager Interface as per below code sample.


 using System;   
 namespace NlogExample.NlogHelper  
 {  
   public interface ILoggerManager  
   {  
     void LogError(string ErrorMessage);  
     void LogError(Exception ex, string ErrorMessage);  
     void LogTrace(string ErrorMessage);  
     void LogDebug(string ErrorMessage);  
     void LogInfo(string ErrorMessage);  
     void LogErrorCsv(Exception ex, string ErrorMessage);  
   }  
 }  

Now next we need to implement new method in loggerManager class added in interface as per below sample.

 using NLog;  
 using System;  
 namespace NlogExample.NlogHelper  
 {  
   public class LoggerManager: ILoggerManager  
   {  
     Logger log = NLog.LogManager.GetLogger("ErrorLogFile");  
     Logger logErrorWithCSV = NLog.LogManager.GetLogger("logErrorWithCSV");  
     public void LogError(string ErrorMessage)  
     {  
       log.Error(ErrorMessage);  
     }  
     public void LogError(Exception ex,string ErrorMessage)  
     {  
       log.Error(ex, ErrorMessage);  
     }  
     public void LogInfo(string ErrorMessage)  
     {  
       log.Info(ErrorMessage);  
     }  
     public void LogDebug(string ErrorMessage)  
     {  
       log.Debug(ErrorMessage);  
     }  
     public void LogTrace(string ErrorMessage)  
     {  
       log.Trace(ErrorMessage);  
     }  
     public void LogErrorCsv(Exception ex, string ErrorMessage)  
     {   
       logErrorWithCSV.SetProperty("CustomProperty", "Value of custom property");  
       logErrorWithCSV.Error(ex,ErrorMessage);  
     }  
   }  
 }  

Now we will call the LogErrorCsv method in our HomeController as below.

 using Microsoft.AspNetCore.Mvc;   
 using NlogExample.Models;  
 using NlogExample.NlogHelper;  
 using System;   
 using System.Diagnostics;  
 namespace NlogExample.Controllers  
 {  
   public class HomeController : Controller  
   {  
     private readonly ILoggerManager _logger;  
     public HomeController(ILoggerManager logger)  
     {  
       _logger = logger;  
     }  
     public IActionResult Index()  
     {  
       _logger.LogInfo("In Index");  
       try  
       {  
         _logger.LogDebug("In Index");  
         int i = 0;  
         _logger.LogTrace("value of i="+i);  
         var output = 75 / i;  
         _logger.LogDebug("out Index");  
       }  
       catch (Exception ex)  
       {  
         _logger.LogError("this is sample error without exception");  
         _logger.LogError(ex, "this is sample error with exception");  
         _logger.LogErrorCsv(ex, "this is sample error with exception");  
       }  
       return View();  
     }  
     public IActionResult Privacy()  
     {  
       return View();  
     }  
     [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]  
     public IActionResult Error()  
     {  
       return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });  
     }  
   }  
 }  

Now we can run the project and we will get the below output.

NLog File Location

NLog csv file output

This way you can easily implement the logging in csv file using Nlog.

 

What Next, Learn how to store logs in SQL server database using NLog in below article. 

Implement Logging in Sql Server Database using Nlog in .net core MVC application - part 3 



  


Comments

  1. Your article is very helpful to implement Nlog however could you please tell what changes should I make it to work for winforms application?

    ReplyDelete
    Replies
    1. Thank you for reply, will publish article regarding winform implementation soon

      Delete

Post a Comment

Popular posts from this blog

Root your Gingerbread 2.3.4 android Mobile Phone

Disable backspace key using Jquery

Restore the lost focus of Auto post back controls in asp.net update Panel control

Implement Nlog in .Net core MVC application part 1

Devexpress Datebox date formatting in angular 6 with example

Angular User Session Timeout example step by step

How to Import CSV File and bind csv file data to gridview in asp.net using c#

Add Comma automatically while entering amounts in textbox using Javascript