Microsoft has collaborated with various third party logging providers like NLog, Serilog, Loggr, Log4Net, etc. to extend the number of Logging Providers.This article demonstrates how to integrate NLog with ASP.NET Core Web Application and log application exceptions to log file.
Introduction
In a real world application, a proper error logging mechanism is essential to track and troubleshoot the unexpected behaviour of the application. In ASP.NET Core, we have built in Logging
API that is included in the Microsoft.Extensions.Logging
which comes as a NuGet
package.
With this API, we can log information to different built in logging providers like Console
, Debug
, EventListener
, TraceListeners
etc. To extend the number of providers, Microsoft has also collaborated with various third party logging providers like NLog
, Serilog
, Loggr
, Log4Net
and some others.
In this article, we will explore ASP.NET Core integration with NLog
, one of the most popular third party logging provider.
Integration Steps
In this article, we will be covering the NLog integration with an ASP.NET Core web application. There are three steps involved in this process. They are:
- Adding NLog NuGet Package
- Adding NLog Configuration
- Adding NLog Provider
Adding NLog NuGet Package
As a first step, we need to install NLog from NuGet package manager.
To do this, right click the Project from Solution Explorer and select Manage NuGet Packages… from the context menu. It will open the Package Manager Solution window.
From the Package Manager window, browse for NLog.Web.AspNetCore
NuGet package as shown in the below image:
Next, select the latest stable version and click Install. At this point of time, the latest version is 4.9.3. If a previous version is required, we can choose from version dropdown.
This will install NLog NuGet package to our project. Once we get the success message, we can move to the next step, i.e., adding NLog configuration.
Adding NLog Configuration
After installing NLog NuGet package, we need to configure it. Configuration information for NLog will be kept inside a configuration file, namely, nlog.config in the application root folder.
This nlog.config is not an auto generated one. So we need to add it manually.
To add nlog.config, right click the Project and select Add then New Item from context menu. From the new item template window, search for Text file.
Name the text file nlog.config as shown in the below image:
NLog configuration file is an XML based configuration file. Below is the minimum configuration required to write the log information to a file.
="1.0"="utf-8"
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="applog" xsi:type="File"
fileName="C:\Log\applog-${shortdate}.log"
layout="${longdate} - ${message} -
${exception:format=StackTrace}${newline}" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="applog" />
</rules>
</nlog>
As per the above configuration, NLog will create log file with the name applog-{today’s date}.log
in the path C:\Log\, if it does not already exist. You can also give any physical path as you require.
The logging rule enforces the minimum level of logging we need.
Here, we are covering only a minimum configuration which will log application exception to a log file. To see more configuration options, please visit NLog Official Documentation in GitHub.
At build time, this configuration file should be copied to the Output directory. To get this done, right click the nlog.config file from the Solution Explorer and select “Properties”.
In the Properties window, under “Advanced” section, go to Copy to Output Directory property and choose Copy if Newer as value.
Now that we have finished the configuration section, we can move to the final step, Adding NLog Provider.
Adding NLog Provider
To add NLog as one of the logging providers, we need to modify the CreateHostBuilder
method in the Program.cs file. The below code snippet will enable NLog logging provider.
.ConfigureLogging((hostingContext, logging) => {
logging.AddNLog(hostingContext.Configuration.GetSection("Logging"));
});
As you can see in the snippet, the logging levels will be applied based on the Logging
configuration provided in the appsettings.json file.
Below is the default logging configuration Visual Studio creates in appsettings.json file while creating new project. You can change this logging level as per your requirement.
For advanced logging level configuration, please visit the Microsoft Official Page.
With this, we have completed NLog integration with our ASP.NET Core Web application. Now let us test the NLog log provider by throwing an exception.
Testing NLog Provider
To test the NLog provider, we are using Microsoft Logging API. As mentioned in the introduction section, the API is included in Microsoft.Extensions.Logging
package which is already added in ASP.NET Core Web application template.
The interface we are using to log error is ILogger
from Microsoft.Extensions.Logging
namespace. ILogger
is already available in application’s dependency container because the WebHost
builder is adding Logging service to dependency container along with other necessary services.
So we can inject the ILogger
type through our HomeController
constructor as shown in the below image:
Next, we have to generate an Exception in the Index
action and log that to the ILogger
object.
Here, we are creating a divided by zero exception and logging to our logger API. Next, we can verify the log file.
Log file is created and exception is logged as per the configuration parameters specified.
Summary
In this article, we covered basic integration steps of NLog library with ASP.NET Core 3.1 web application. There are few other third party logging providers which are also available as NuGet packages.
History
- 12th August, 2020: Initial version