Create logs with NLog in Asp.Net MVC

I will show today a simple example of how to log using NLog in an ASP.NET MVC application. Nlog is an awesome, simple logging solution for .NET.  NLog can be used to write logs to Files, database, Event logs and ASP.NET Trace files. We always have exceptions in our applications for that log files are widely used.

Open your project in DotNet, go to Solution Explorer. Right click on References and select Manage NuGet Package to get NLog.

Now search for NLog and click on install.

 NugetNLog.png, Exception Loging, Asp.Net, NLog, Exception,

To setup and create NLog object for loging we are going to add helper class Nlogger.cs. In this class we will define rules and layout to generate the log output. With Nlog we can define different targets to write log which I may add in my next blog.

Create a folder named ErrorLog in your solution, and make sure you have given all permissions to write a log file into it.

public class NLogger
        public static Logger LogWrite()
            Logger log;
            // Step 1. Create configuration object 
            var config = new LoggingConfiguration();

            // Step 2. Create targets and add them to the configuration 
            var consoleTarget = new ColoredConsoleTarget();
            config.AddTarget("console", consoleTarget);

            var fileTarget = new FileTarget();
            config.AddTarget("file", fileTarget);

            // Step 3. Set target properties 
            consoleTarget.Layout = @"${date:format=yyyy-MM-ddTHH\:mm\:ss} ${logger} ${message}";
            fileTarget.FileName = "${basedir}/weblog.txt";
            fileTarget.Layout = @"--------------------- ${level}(${longdate})${windows-identity:domain=false}-------------------- ${newline}      
            Controller/ Method Name: ${callsite}${newline}
            Exception Type: ${exception:format=Type}${newline}  
            Message: ${exception:format=Message}${newline}
            Stack Trace: ${exception:format=Stack Trace}${newline}    
            User Info: ${message}${newline}";

            // Step 4. Define rules
            var rule1 = new LoggingRule("*", LogLevel.Debug, consoleTarget);

            var rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget);

            // Step 5. Activate the configuration
            LogManager.Configuration = config;

            // usage
            log = LogManager.GetLogger("TestWebLog");
            return log;

Note that I added ${basedir} means web application root in the file path. The filename will be the file written to the ErrorLog directory.

The logger will write the following information to the file:

  1. ${longdate} : a datetime stamp
  2. ${level} : the log level
  3. ${message}: the custom message you wish to log
  4. ${windows-identity:domain=false} : the wedsite user. If unauthenticated, then this will be blank.
  5. ${callsite} : location of the error occurred
  6. ${exception:format=Type} : the type of exception occurred
  7. ${exception:format=Message}: the exception message
  8. ${exception:format=Stack Trace} : Stack Trace defining source of exception.


Rules for NLog:
var rule1 = new LoggingRule("*", LogLevel.Debug, consoleTarget);

var rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget);

The above rules instructs NLog to log all the entries at Debug level and above to both targets. NLog defines the following Log Levels:

  • Trace - very detailed logs, which may include high-volume information such as protocol payloads. This log level is typically only enabled during development
  • Debug - debugging information, less detailed than trace, typically not enabled in production environment.
  • Info - information messages, which are normally enabled in production environment
  • Warn - warning messages, typically for non-critical issues, which can be recovered or which are temporary failures
  • Error - error messages
  • Fatal - very serious errors

Above all configuration changes are done, then final step is to create a Nlogger object in our application and start logging.

Now create ErrorController, we will use index method to generate DivideByZeroException. Finally we will use LogWrite().Error(expection, message) to write log to server as LogWrite().ErrorException() has become obsolete.

NLogger LogWrite is a static method which returns NLog logger object so we are going to use NLogger.LogWrite().Error().


        public ActionResult Index()
                int x = 0;
                int y = 5;
                int z = y / x;
            catch (Exception ex)
                NLogger.LogWrite().Error(ex, "Error occured in Home controller Index Action");


            return View();

Following output is generated in weblog.txt when we run index page of ErrorController.


Errorlogfile.png, Exception Loging, Asp.Net, NLog, Exception,

Back to top