There's official update for NLog targeting ASP.NET Core 2.x, for the latest methods please refer to https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2

Recently I am porting a classic ASP.NET MVC 5 project to .NET Core 2.0, in order to run it on Linux. One of the parts that has differences between .NET Fx and .NET Core is logging. I choose NLog as my logging providor, let's see how to port this to .NET Core.

Migrating Configuration File


First, let's see the .NET Framework version of nlog.config

<?xml version="1.0"?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <targets>
    <target name="file" xsi:type="File" fileName="${basedir}/App_Data/Logs/${shortdate}.txt" encoding="utf-8" layout="[${longdate}][${machinename}][${level}] ${message} ${exception}" />
  </targets>
  <rules>
    <logger name="*" minlevel="Trace" writeTo="file" />
  </rules>
</nlog>

This basically is write the log in text files under the website's App_Data directory.

In order for this to work in .NET Core, it requires changes, the new config file is:

<?xml version="1.0"?>
<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>
  
  <targets>
    <target name="allfile" xsi:type="File" 
            fileName="${basedir}\logs\GDStationaryNetCore\${shortdate}.log" 
            encoding="utf-8" 
            layout="[${longdate}][${machinename}][${level}] ${message} ${exception}" />
  </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>

The location for the nlog.config file is still under your project's root directoy.

In this example, the most important part is that ASP.NET Core extentions must be added to the configuration.

When use it in production, I would strongly recommend turn off Microsoft logs, so that your log will not be flooded with the host process's information.

Add NLog Package for ASP.NET Core 2.0


Use NuGet to install this package into your ASP.NET Core 2.0 project:

PM > Install-Package NLog.Web.AspNetCore

Register NLog


In Startup.cs, add the following code. 

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
	...
    env.ConfigureNLog("nlog.config");
	...

    // make sure Chinese chars don't fk up
    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); 

    //add NLog to ASP.NET Core
    loggerFactory.AddNLog();

    //add NLog.Web
    app.AddNLogWeb();
}

DI into Controller


Add a logger object to your Controller.

protected readonly ILogger<YourController> _logger;

Modify the constructor to use DI

public YourController(ILogger<YourController> logger = null)
{
    if (null != logger)
    {
        _logger = logger;
    }
}

Use Logging APIs


Now, you can use the logging APIs like this:

_logger.LogInformation($"Created OrderId: {order.OrderId}, FriendlyId: {order.FriendlyId}, User: {user.UserName}.");

The API names changed a little bit. It use to be Info(), Error().. etc. Now it is LogInformation() etc... 

Now, run your app, you should see logs coming up: