ASP.NET MVC Logging using NLog Step by step Implementation and Top 10 Questions and Answers
 Last Update: April 01, 2025      9 mins read      Difficulty-Level: beginner

ASP.NET MVC Logging using NLog: A Step-by-Step Guide

Introduction

Logging is an essential aspect of application development, helping developers diagnose issues, monitor system behavior, and trace errors. As applications grow in complexity, effective logging becomes increasingly critical for maintaining and scaling them. One of the powerful and flexible logging frameworks available for .NET applications is NLog. This guide will walk you through the process of integrating NLog into an ASP.NET MVC application, step-by-step.

Step 1: Understanding Logging Basics

Before diving into NLog, it's helpful to understand some basic logging concepts:

  • Log Message: A single entry in a log file, containing information about an event or action that occurred in the application.
  • Log Level: The severity of the log message (e.g., Debug, Info, Warn, Error, Fatal).
  • Log Target: A destination for the log messages (e.g., file, database, console).
  • Log Configuration: Settings that define how log messages are formatted, which log levels are included, and where log messages are sent.

Step 2: Setting Up Your ASP.NET MVC Project

First, create a new ASP.NET MVC project if you haven't already. You can do this through Visual Studio:

  1. Open Visual Studio.
  2. Select "Create a new project".
  3. Choose "ASP.NET Web Application (.NET Framework)".
  4. Name your project and choose the MVC template.
  5. Click "Create".

Step 3: Installing NLog via NuGet

NLog can be easily added to your project using NuGet, the .NET package manager:

  1. In Solution Explorer, right-click on your project.
  2. Select "Manage NuGet Packages...".
  3. In the NuGet Package Manager, go to the "Browse" tab.
  4. Search for "NLog.Web.AspNetCore" (if you are using ASP.NET Core) or "NLog" (if you are using classic ASP.NET).
  5. Click "Install".

Step 4: Configuring NLog

NLog uses an XML configuration file named NLog.config. You need to create this file in your project:

  1. Right-click on your project in Solution Explorer.
  2. Select "Add" -> "New Item...".
  3. Choose "XML File".
  4. Name the file "NLog.config".

Add the following content to the NLog.config 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"
      autoReload="true"
      throwConfigExceptions="true">

    <!-- Optional: include asp.net core layout renderers -->
    <extensions>
        <add assembly="NLog.Web.AspNetCore"/>
    </extensions>

    <targets>
        <target xsi:type="File" name="file" fileName="logs/app-${shortdate}.log"
                layout="${longdate} ${uppercase:${level}} ${logger} ${message} (${callsite:className=true:includeSourcePath=false:fileName=false:methodName=false:skipFrames=2} )"/>
        
        <target xsi:type="Console" name="console"
                layout="${longdate} ${uppercase:${level}} ${logger} ${message} ${exception:format=tostring}"/>
    </targets>

    <rules>
        <!-- Add your logging rules here -->
        <logger name="*" minlevel="Debug" writeTo="file,console" />
    </rules>
</nlog>

This configuration sets up two targets: a file target for logging to a file named app-yyyyMMdd.log in a logs folder, and a console target for logging to the console.

Step 5: Initializing NLog in Global.asax.cs (for ASP.NET MVC)

For classic ASP.NET MVC, you need to initialize NLog in the Global.asax.cs file:

  1. Open the Global.asax.cs file.
  2. At the top of the file, ensure you have using NLog;.
  3. Add the following code within the Application_Start method:
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    var logger = LogManager.GetCurrentClassLogger();
    logger.Debug("Application_Start");
}
  1. Optionally, add a shutdown hook to ensure NLog flushes its logs when the application is shutting down:
protected void Application_End()
{
    LogManager.Shutdown();
}

Step 6: Logging in Controllers

Now that you have set up NLog, you can start logging in your controllers or other classes:

  1. Open a controller, e.g., HomeController.cs.
  2. At the top of the file, ensure you have using NLog;.
  3. Add a logger field and constructor to the class:
public class HomeController : Controller
{
    private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();

    public ActionResult Index()
    {
        Logger.Info("Visiting the Index page");
        ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
        
        return View();
    }

    public ActionResult About()
    {
        Logger.Debug("Visiting the About page");
        ViewBag.Message = "Your application description page.";
        return View();
    }

    public ActionResult Contact()
    {
        Logger.Warn("Visiting the Contact page");
        ViewBag.Message = "Your contact page.";
        return View();
    }
}

Step 7: Handling Exceptions

NLog can also help you log exceptions. You can use try-catch blocks to log exceptions and handle them appropriately.

For example, add a new action method to HomeController.cs to handle exceptions:

public ActionResult Error()
{
    try
    {
        // Simulate an error
        int result = 10 / 0;
    }
    catch (Exception ex)
    {
        Logger.Error(ex, "An error occurred in the Error action method");
    }
    
    return View();
}

Step 8: Advanced Logging Features

NLog offers many advanced features, such as:

  • Layouts: Custom formatting for log messages.
  • Filters: Conditional logging.
  • Targets: Additional logging targets, such as databases, email, event logs, etc.
  • Log Context: Adding contextual information to log messages.

For example, to include the request URL in log messages, modify the NLog.config file layout:

<layout xsi:type="JsonLayout">
    <attribute name="time" layout="${longdate}" />
    <attribute name="level" layout="${uppercase:${level}}" />
    <attribute name="logger" layout="${logger}" />
    <attribute name="message" layout="${message}" />
    <attribute name="url" layout="${aspnet-request-url}" />
    <attribute name="referrer" layout="${aspnet-request-url-referrer}" />
    <attribute name="exception" layout="${exception:format=tostring}" />
    <attribute name="callsite" layout="${callsite:className=true:includeSourcePath=false:fileName=false:methodName=false:skipFrames=2}" />
</layout>

Step 9: Testing Your Configuration

To ensure that your NLog configuration is working correctly, run your application and perform actions that trigger logging. You should see log messages in both the console and the log file.

  • Open a browser and navigate to different pages like Index, About, Contact, and Error.
  • Check the console for log messages.
  • Navigate to the logs folder in your project directory and open the log file to verify the log messages are being written to it.

Conclusion

Integrating NLog into your ASP.NET MVC application provides robust logging capabilities, making it easier to monitor and debug your application. By following the steps outlined in this guide, you've learned how to set up NLog, configure it, and use it to log messages and handle exceptions in your application. As you become more familiar with NLog, you can explore its advanced features to further enhance your logging strategy. Happy coding!