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 .

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.

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.