ASP.NET Core logging integration using NLog

Kailash Chandra Behera | Wednesday, August 30, 2023

Introduction

In my previous blog posts, I have provided the details how to implement the log4net in .Net applications which are given below. Here we will discuss how to implement logging in ASP.NET Core using NLog.

  1. How to use log4net in C#
  2. log4net ASP NET MVC Example
  3. log4net Configuration for Multiple Files
  4. How to use log4net in WPF

Getting Started

NLog is not an inbuild library of Microsoft .Net programming. It is a third-party library. Microsoft has collaborated with various logging providers to extend the number of logging providers in ASP.NET core. We will use the NLog here for web API logging.

Various Loging Providers in ASP.NET Core

  • Log4Net: One of the greatest logging tools out there for .NET is log4net. This software is the gold standard for how logging should be done. It is simple, powerful, and extensible.

  • Nlog: NLog is a flexible and free logging platform for various .NET platforms, including .NET standard. NLog makes it easy to write to several targets. (Database, file, console) and change the logging configuration on-the-fly.

  • SerialLog: Serilog is a diagnostic logging library for .NET applications. It is easy to set up, has a clean API, and runs on all recent .NET platforms. Serilog's support for structured logging shines when instrumenting complex, distributed, and asynchronous applications and systems.

  • Logger: Loggr is a cloud-based, real-time web application monitoring, includes monitoring application events and user monitoring.

Here we will explore implementing logging in ASP.NET core web API with .Net Core 6. If you don’t know how to create web API in .net core, then visit my blog post that contains how to create API with .net core. If you know then you can continue this web API logging demonstration.

To integrate the .net core API logging with NLog, there are only three steps given below.

  • Install NLog.
  • Add Nlog Config.
  • Add NLog as logging provider.

Install NLog in .Net Core 6

The NLog library is available in NuGet Package, to install it you need to download from NuGet Package. To download the library, follow the below steps.

  1. Right click on the project from solution explorer.
  2. Select Manage NuGet Package from the context menu, the Package Manager window will be opened.

  3. Browse NLog from the Package Manager window, you will get the NLog.Web.AspNetCore as shown in the below Image.

    web application logs
  4. On the right pan, select the latest stable version and click install. I have installed the 5.3.3 version as the latest one.

  5. If the NLog installed successfully then you will get following out put as shown below image.

     

    visual studio nuget

  6. If it fails, then you need to take action to remove the error message.

Configuration application for NLog

After successfully installing, you need to add NLog config information into the project. If you use log4net before unlike log4net the configuration information is not generated in configuration file (web.config or app.config file) automatically. Manually you need to add information.

The configuration is formatted as XML and is either embedded in a Visual Studio project config file or is stand-alone xml file.

Embedding Nlog Config

Config XML is case-insensitive for xml-nodes and xml-attributes, when not using a namespace and is case-sensitive when using a namespace. Configuration is either embedded in a Visual Studio project config file or is stand-alone xml file. Follow the below steps to embed NLog config.

  • Open you project config file (app.config / web.config).
  • Find the configSessions element, copy the below nlog section and paste inside the confiSessions like below.
     <configSections>  
       <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>  
     </configSections>  
    
  • Copy the below nlog elements and paste inside the configuration section.
     <nlog>  
       <targets>  
         <target name="logconsole" xsi:type="Console" />  
       </targets>  
       <rules>  
         <logger name="*" minlevel="Info" writeTo="logconsole" />  
       </rules>  
     </nlog>  
    
  • The nlog should placed inside the configuration like below.
     <configuration>  
      <configSections>  
       <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>  
      </configSections>  
      ...  
      <nlog>  
       <targets>  
         <target name="logconsole" xsi:type="Console" />  
       </targets>  
       <rules>  
         <logger name="*" minlevel="Info" writeTo="logconsole" />  
       </rules>  
      </nlog>  
     </configuration>  
    

Add Stand-alone Nlog Config

To add a configuration file, follow the below mentioned steps

  • Right click the project then select add new item from context menu.
  • From the new item template window, search for text file.
  • Enter the name of the file, for example Nlog.config then click on the Add button.
  • Copy the below xml content and paste it in your newly created file. It the minimum configuration require that write logs 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">  
       <targets>  
         <target name="logfile" xsi:type="File" fileName="file.txt" />  
         <target name="logconsole" xsi:type="Console" />  
       </targets>  
       <rules>  
         <logger name="*" minlevel="Info" writeTo="logconsole" />  
         <logger name="*" minlevel="Debug" writeTo="logfile" />  
       </rules>  
     </nlog>  
    
  • Then save it again. Right click on the Nlog.conf file from the solution explorer and select “Properties”.
  • In the proprieties window under the “Advanced”, choose “Copy if Newer for the Copy to Output Directory.
  • Point number is 6 required because at the build time this configuration file is required inside the output directory.
  • Now we have finished the Nlog configuration.

Enable NLog Logging provider.

After successfully adding the configuration information to the project, the next step is to enable Nlog logging provider as one of the logging providers in Asp.net core. The following code enables NLog logging provider for web API logging. See the code carefully and apply the change in your in the program file.

 //configure logging  
   builder.Services.AddLogging(loggingBuilder =>  
   {  
     loggingBuilder.ClearProviders();  
     loggingBuilder.AddNLog();  
   });  
Programm file codes
 var builder = WebApplication.CreateBuilder(args);  
   // Add services to the container.  
   builder.Services.AddControllers();  
   // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle  
   builder.Services.AddEndpointsApiExplorer();  
   builder.Services.AddSwaggerGen();  
   //configure logging  
   builder.Services.AddLogging(loggingBuilder =>  
   {  
     loggingBuilder.ClearProviders();  
     loggingBuilder.AddNLog();  
   });  
   var app = builder.Build();  
   // Configure the HTTP request pipeline.  
   if (app.Environment.IsDevelopment())  
   {  
     app.UseSwagger();  
     app.UseSwaggerUI();  
   }  
   app.UseHttpsRedirection();  
   app.UseAuthorization();  
   app.MapControllers();  
   app.Run();  

Setting up Log Level .Net Core

Now we are successfully integrated Nlog library into ASP.NET Core web API. The next step is changing the logging level as per own requirements from the default level. Microsoft in appSetting.json file provides log levels with minimum requirements as shown in below code.

 {  
  "Logging": {  
   "LogLevel": {  
    "Default": "Information",  
    "Microsoft": "Warning",  
    "Microsoft.Hosting.Lifetime": "Information"  
   }  
  }  
 }  

You can change the default level by setting in Loggin.{providername}.LogLevel and override settings in Logging.Loglevel. You can add different log level according to your requirements like below code.

 {  
  "Logging": {  
   "LogLevel": { // All providers, LogLevel applies to all the enabled providers.  
    "Default": "Error", // Default logging, Error and higher.  
    "Microsoft": "Warning" // All Microsoft* categories, Warning and higher.  
   },  
   "Debug": { // Debug provider.  
    "LogLevel": {  
     "Default": "Information", // Overrides preceding LogLevel:Default setting.  
     "Microsoft.Hosting": "Trace" // Debug:Microsoft.Hosting category.  
    }  
   },  
   "EventSource": { // EventSource provider  
    "LogLevel": {  
     "Default": "Warning" // All categories of EventSource provider.  
    }  
   }  
  }  
 }  

Testing NLog

To test the logging functionalities, create logging instance in controller and use it in the action as like given below code.

 using Microsoft.AspNetCore.Mvc;  
 using Microsoft.Extensions.Logging;  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Threading.Tasks;  
 namespace NLog.Controllers  
 {  
   [ApiController]  
   [Route("[controller]")]  
   public class WeatherForecastController : ControllerBase  
   {  
     private static readonly string[] Summaries = new[]  
     {  
       "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"  
     };  
     private readonly ILogger<WeatherForecastController> _logger;  
     public WeatherForecastController(ILogger<WeatherForecastController> logger)  
     {  
       _logger = logger;  
     }  
     [HttpGet]  
     public IEnumerable<WeatherForecast> Get()  
     {  
       try  
       {  
         var rng = new Random();  
         return Enumerable.Range(1, 5).Select(index => new WeatherForecast  
         {  
           Date = DateTime.Now.AddDays(index),  
           TemperatureC = rng.Next(-20, 55),  
           Summary = Summaries[rng.Next(Summaries.Length)]  
         })  
         .ToArray();  
       }  
       catch (Exception ex)  
       {  
         _logger.Error(ex, "Error in init");  
         throw;  
       }  
       finally  
       {  
         _logger.LogManager.Shutdown();  
       }  
     }  
   }  
 }  

Summary

In this blog post ASP.NET Core logging integration using NLog, we demostration how to add Nlog as logging provider into project by overriding the default logging providers in ASP.NET Core. I hope this post is helpfult to you.

Thanks


No comments: