Error and Exception Logging Using NLog in an ASP.NET MVC Application

Error Logging is one of the key attributes of application development. Most of the applications we write must have the logging mechanism to see the error log when some exception happens. We write lots of unit testing, do lots of manual testing in development but still there are some points we cannot anticipate will cause an error.

For example some code works fine in local machines, staging, and UAT but when it goes to production it fails. So where to look for what could be the issue? As we know, in production environments most of the systems don’t have Visual Studio to debug the code. To see these exception errors, log files are used widely.

NLog is a very good logging framework to achieve logging in .NET Applications. It is very easy to configure and logging information can be written to Files, database, Event logs and ASP.NET Trace files.
 
Let us see a simple example of how to log using NLog in an ASP.NET MVC application.

Now we will create a sample ASP.NET MVC application and get the NLog Library references using Nuget.



We have the NLog from the Nuget now. We will create a config file named NLog.config as shown below to the project.

NLog.Config File,
  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" throwExceptions="false" internalLogFile="G:\NLogErrors\log.txt">  
  3.     <extensions>  
  4.         <!-- load NLog.Extended to enable ASP.NET-specific functionality -->  
  5.         <add assembly="NLog.Extended" />  
  6.     </extensions>  
  7.     <!--Define Various Log Targets like files, database or asp.net trace files-->  
  8.     <targets>  
  9.         <target name="console" xsi:type="ColoredConsole" layout="${message}" />  
  10.         <!--Write logs to File  where we want to write error logs-->  
  11.         <target name="file" xsi:type="File" fileName="G:\NLogErrors\ErrorLogFile.log" layout="      
  12.             --------------------- ${level}(${longdate})${machinename}-------------------- ${newline}      
  13.             ${newline}      
  14.             Exception Type:${exception:format=Type}${newline}      
  15.             Exception Message:${exception:format=Message}${newline}      
  16.             Stack Trace:${exception:format=Stack Trace}${newline}      
  17.             Additional Info:${message}${newline}      
  18.             ">  
  19.         </target>  
  20.   
  21.     </targets>  
  22.   
  23.     <rules>  
  24.         <logger name="*" minlevel="trace" writeTo="file" />  
  25.   
  26.     </rules>  
  27. </nlog>  

We will write some code for logging. In the Home Controller, Index action, we will create a exception forcibly and write it into logger using logger.ErrorException() method.

Controller Code
  1. using NLog;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace NlogWithMVC.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         Logger logger = LogManager.GetCurrentClassLogger();    
  13.         public ActionResult Index()  
  14.         {  
  15.   
  16.   
  17.             try  
  18.             {  
  19.                 int x = 0;  
  20.                 int y = 5;  
  21.                 int z = y / x;  
  22.             }  
  23.             catch (Exception ex)  
  24.             {  
  25.                 logger.ErrorException("Error occured in Home controller Index Action", ex);  
  26.               
  27.             }  
  28.             return View();  
  29.         }  
  30.   
  31.         public ActionResult About()  
  32.         {  
  33.             ViewBag.Message = "Your application description page.";  
  34.   
  35.             return View();  
  36.         }  
  37.   
  38.         public ActionResult Contact()  
  39.         {  
  40.             ViewBag.Message = "Your contact page.";  
  41.   
  42.             return View();  
  43.         }  
  44.     }  
  45. }  

When we run the page we see that the log file is created at the file which is defined in the NLog.Config file.

Output when we run the page is as shown below



We saw how to handle logging in an ASP.NET MVC application using NLog. Thanks for reading.