How to Configure NLog in ASP.NET Core

In my earlier article, I explained how to configure error logging module (ELM) in Asp.net Core. ELM Microsoft's own logging framework but it has limited functionality and not recommended for enterprise applications. NLog comes to save the day for provide better logging facility. Today,  I am going to explain how to configure the NLog library into the  Asp.net Core project.

What is NLog?

NLog is free logging platform for .NET, NET Standard, Xamarin, Silverlight and Windows Phone with rich log routing and management capabilities. NLog makes it easy to produce and manage high-quality logs for your application regardless of its size or complexity. NLog is easy to configure, templatable and extensible to us it more effectively.

Add NLog to ASP.NET Core

Setup new ASP.NET Core project with visual studio 2015+. You can choose any project type either MVC or web.API, NLog will work with both.
Install swagger from nuget using package manager console.
PM> Install-Package NLog.Web.AspNetCore
Here, 4.3.1 version will be installed in the project.

Create a nlog.config file

Create new config file and named it nlog.config. This file is required by Nlog to configure NLog logging options. More nlog.config related information is available here .
<?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"
      internalLogLevel="Warn"
      internalLogFile="c:\temp\internal-nlog.txt">

  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>
  
  
  <!-- define various log targets -->
  <targets>
    <!-- write logs to file -->
    <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log"
                 layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />

   
    <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-own-${shortdate}.log"
             layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|  ${message} ${exception}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />

    <target xsi:type="Null" name="blackhole" />
  </targets>

  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />

    <!--Skip Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>

Configure NLog

Open Startup.cs class and navigate to Configure method to add below codes. Here, loggerFactory.AddNLog() will add NLog to Asp.net Core, app.AddNLogWeb() will configure NLog web into the the project and env.ConfigureNLog("nlog.config") will consider and configure nlog.config from the project root.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    //add NLog to ASP.NET Core
    loggerFactory.AddNLog();
            
    //add NLog.Web
    app.AddNLogWeb();
            
    //needed for non-NETSTANDARD platforms: configure nlog.config in your project root. NB: you need NLog.Web.AspNetCore package for this.         
    env.ConfigureNLog("nlog.config");

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

Start logging

Once the configuration has been done, inject the ILogger in to Controllers to implement custom logging.
public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
    _logger = logger;
    }

    public IActionResult Index()
    {
    _logger.LogInformation("Hello World!");
    return View();
    }
}
Now run the project, we will get two files having name "nlog-all-2017-04-15.log" and "nlog-own-2017-04-15.log". nlog-all-2017-04-15.log file contains all system level logs and nlog-own-2017-04-15.log file contains custom logs.
nlog-own-2017-04-15.log
2017-01-15 07:31:27.4314||HomeController|INFO|  Hello World! |url: http://localhost/|action: Index
That's all for now. In next article, I will explain how to save NLog logs into sql server.

References