Hackernoon logoIntegrating Logging Using NLog in ASP.NET Core 3.0 Web App by@yashpal

Integrating Logging Using NLog in ASP.NET Core 3.0 Web App

Author profile picture

@yashpalYashpal Pitroda

NLog: It is an open source logging framework that provides a great flexibility and configurable options to log the insights of your application. It allows to select multiple targets like database, cloud services, files, console, etc. at the same time so that user don’t have to maintain different configurations in code. This is the most widely used logging framework out there.
Some of the important features are:
  1. It’s easy to configure
  2. It is based on templates
  3. It has pre-defined layouts so that you can modify messages with custom data
  4. It provides structured logging
Official website of open source project: https://nlog-project.org/
Creating ASP.NET Core project
Step 1: Open Visual Studio 2019 and create a new project.
Step 2: Select ASP.NET Core Web Application from project templates.
Step 3: Choose the name of the project and click Create button.
Step 4: Select Web Application Template and make appropriate selections shown below.
Step 5: The above 4 steps will create an ASP.NET Core 3 Web Application with some default files and folders.
As we have to integrate NLog in the application, we need to install some packages from NuGet package manager.
1. NLog.Web.AspNetCore – This is the package that will install NLog packages.
2. NLog.config – This package will add a config file where we can define all the rules and targets for NLog configuration. NLog libraries will read all configuration from this file.
Step 6: Once we add the required packages, lets create a configuration in NLog.config where we will define a target which will write logs to a file on our local system.
Replace the automatically generated code with the below code in NLog.config 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"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
 
  <targets>
    <target xsi:type="File" name="fileTarget" filename="..\logs\log.txt"></target>
  </targets>
 
  <rules>
    <logger name="*" minlevel="Trace" writeTo="fileTarget" />
  </rules>
</nlog>
We also need to make change to the property of this file so that this file can be copied to directory at the time of application deployment.

Right click on NLog.config file and select properties option and please make the changes as shown below.
Step 7: Once we add the target to file in config file, we have to register NLog as a service in Program.cs file so that I can capture logs and send them to the defined target.
Replace the code in Program.cs file with the below highlighted.
public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureLogging((hostingContext, logging) =>
                {
                    logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                    logging.AddDebug();
                    logging.AddNLog();
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
At the time of WebHost creation, we are injecting logging before calling Startup.cs file. ConfigureLogging method highlighted above is adding logs to two services.

One is Debug windows which is a feature of Visual Studio and Other one is NLog.

AddNLog method is a part of Nuget package that we installed in above steps.

AddConfiguration method is trying to read logging configuration which is by default created by Asp.Net Core project template.

We can also define NLog as service in Startup.cs class. The reason behind calling this before startup class is that sometimes there are some runtime issues that can be caused before Startup class is called, so we will be able to capture them as well.

Step 8: Now run the application and you will find that a log file is created in bin folder of your project.
Note: You can specify any path in the file name property in NLog.config and this will create a log file there. There are a lot of customizations that you can do in NLog config file. Take a look at them at the asp.net mvc development official website mentioned in the starting section of this article.


































Tags

The Noonification banner

Subscribe to get your daily round-up of top tech stories!