Click here to Skip to main content
14,667,121 members
Articles » Web Development » ASP.NET » General
Tip/Trick
Posted 12 Aug 2020

Stats

2.6K views
33 downloads
3 bookmarked

Integrating NLog with ASP.NET Core Web Application

Rate this:
0.00 (No votes)
Please Sign up or sign in to vote.
0.00 (No votes)
12 Aug 2020CPOL
Error logging in ASP.NET Core Application with NLog
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:

Image 1

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.

Image 2

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.

Image 3

Name the text file nlog.config as shown in the below image:

Image 4

NLog configuration file is an XML based configuration file. Below is the minimum configuration required to write the log information to a file.

<?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">
    <!-- the targets to write -->
    <targets>
        <!-- write to file -->
        <target name="applog" xsi:type="File" 

        fileName="C:\Log\applog-${shortdate}.log"

        layout="${longdate} - ${message} - 
        ${exception:format=StackTrace}${newline}" />
    </targets>
    <!-- rules to map from logger name to target -->
    <rules>
        <!-- all logs including Microsoft -->
        <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.

Image 5

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.

Image 6

.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.

Image 7

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:

Image 8

Next, we have to generate an Exception in the Index action and log that to the ILogger object.

Image 9

Here, we are creating a divided by zero exception and logging to our logger API. Next, we can verify the log file.

Image 10

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Sreejith Gopinathan
Software Developer (Senior) Cognizant Technology Solutions
India India
I work as a Technology Specialist in Cognizant Technology Solutions. I have 1.5 decades of experience in Software Development and focuses on Microsoft Web Technologies, JavaScript Frameworks, Azure Services and DevOps

Comments and Discussions

 
-- There are no messages in this forum --