How to use NLog in ASP.Net Core

Take advantage of dependency injection and NLog to build custom logging middleware for your ASP.Net Core application

How to use NLog in ASP.Net Core
Getty Images

NLog is a free, open-source, and easy-to-use logging framework that supports .Net Core and ASP.Net Core as well as the .Net Framework, Xamarin, and other Microsoft platforms. NLog is easy to configure and extend and comes with excellent support for log routing and management capabilities. This makes it a good choice when you must choose a logging framework that is fast and flexible.

In one of my earlier posts here, I covered the basics of NLog and how it can be used to log data to a file using .Net. In this article we will explore how we can take advantage of ASP.Net Core’s built-in support for dependency injection to use NLog as middleware.

Create an ASP.Net Core Web API project

If you’re running Visual Studio 2017, you can follow the steps outlined below to create an ASP.Net Core Web API project.

  1. Launch the Visual Studio IDE. 
  2. Click on File > New > Project.
  3. Select “ASP.Net Core Web Application (.Net Core)” from the list of templates displayed.
  4. Specify a name for the project.
  5. Click OK to save the project.
  6. Select “API” in the “New .Net Core Web Application…” window.
  7. Select the version of ASP.Net Core you want to use.
  8. Uncheck the “Enable Docker Support” box and select “No Authentication” as we won’t be using either of these here.
  9. Click OK.

This will create a new ASP.Net Core Project in Visual Studio 2017. Next, install the following two packages to the project via the NuGet Package Manager in Visual Studio: 

NLog.Config
NLog.Web.AspNetCore

Register NLog in your .Net Core project 

Once NLog has been installed in your project, the next step is to register it. To register NLog with the pipeline in your ASP.NET Core project, you can write the following code in the Startup.cs file.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, LoggerFactory loggerFactory)
        {
            env.ConfigureNLog(“nlog.config”);
            loggerFactory.AddNLog();
            app.AddNLogWeb();
            //Other code
        }

The first statement will configure NLog with the hosting environment instance. The other two statements will add NLog and NLog.Web respectively to the pipeline.

Use NLog in ASP.Net Core controllers

Now that you have installed and configured NLog in your project, you can now leverage dependency injection to start using NLog in your controllers. Here is an example code snippet that illustrates this.

public class ValuesController : ControllerBase
 {
        protected readonly ILogger<ValuesController> _logger;
        public ValuesController(ILogger<ValuesController> logger = null)
        {
            if (null != logger)
            {
                _logger = logger;
            }
        }
      //Other controller methods
 }

Now refer to the ValuesController class given earlier. Note how constructor injection has been used here to inject the dependency, i.e., the logger instance.

And that’s all there is to it. You can now start logging your application data in any of your controller methods using the following code.

[HttpGet]
 public ActionResult<IEnumerable<string>> Get()
  {
      _logger.LogInformation(“This is an info message sent from values controller.”);
      _logger.LogDebug(“This is a debug message sent from values controller.”);
      _logger.LogWarning(“This is a warning message sent from the values controller.”);
      _logger.LogError(“This is an error message sent from the values controller.”);
      return new string[] { “Hello”, “World!” };
  }

A good design approach will be to abstract the logging capabilities to a middleware component and inject it into the pipeline. In doing this, you can change your middleware component without having to make any changes to your controller methods.

Build a logging middleware component in ASP.Net Core

Let’s now build a simple middleware component, inject it into the pipeline, and then use it in the controller methods. Here is an interface that contains the declaration of methods to log data at various levels.

public interface ILoggerManager
    {
        void LogInformation(string message);
        void LogWarning(string message);
        void LogDebug(string message);
        void LogError(string message);
    }

The LoggerManager class implements the methods of the ILoggerManager interface as shown in the code listing below.

    using NLog;
    public class LoggerManager : ILoggerManager
    {
        private static NLog.ILogger logger = LogManager.GetCurrentClassLogger();
        public LoggerManager()
        {
        }
        public void LogDebug(string message)
        {
            logger.Debug(message);
        }
        public void LogError(string message)
        {
            logger.Error(message);
        }
        public void LogInformation(string message)
        {
            logger.Info(message);
        }
        public void LogWarning(string message)
        {
            logger.Warn(message);
        }
    }

Support for dependency injection is built into ASP.Net Core. Both framework services and application services can be injected into your classes, rather than being tightly coupled. Now that the custom LoggerService is ready, you can inject it right into the pipeline using the ConfigureServices method in the Startup.cs file. There are three ways to do this. (You can read more about using dependency injection in ASP.Net Core in one of my earlier posts here.”)

In this example we will take advantage of the “singleton” way of injecting dependency — i.e., a single instance will be created and shared. The following line of code illustrates how we can inject an instance of LoggerManager into the pipeline.

services.AddSingleton<ILoggerManager, LoggerManager>();

And here finally is how you can use the logger middleware in your controllers.

public class ValuesController : ControllerBase
 {
  protected readonly ILoggerManager _logger;
   public ValuesController(ILoggerManager logger = null)
   {
       if (null != logger)
       {
           _logger = logger;
       }
   }
 }

NLog is a fast logging platform that is also easy to configure. As we have seen, it is quite easy to build a custom middleware component in ASP.Net Core that takes advantage of NLog to log application data.

Copyright © 2018 IDG Communications, Inc.