Joydip Kanjilal
Contributor

How to use NLog in ASP.NET Core

how-to
Sep 03, 20185 mins
C#Small and Medium BusinessSoftware Development

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

11 event logging
Credit: 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.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author