Implementation Of NLog With .NET 6 Web API

As a Modern web application, we do a lot of operations in it. To handle more requests, we need a robust logging mechanism for monitoring.

Henceforth I've shared One of the best logging mechanisms implemented for the .NET 6 web application.

By default, Microsoft has a logging mechanism, but for our convenience, we go with third-party log providers, which is helpful to make how we need our logs to be said, for example, file, console, etc...

I'm using NLog as a third-party log provider (you can learn more about NLog here NLog under config options).

Hereby I've given some short notes about logs done in NLog. For NLog configuration, you need the "NLog.config" file. Inside that, you have an XML file describing the logging configuration.

NLog.config 

<?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">
  <!--
  See https://github.com/nlog/nlog/wiki/Configuration-file
  for information on customizing logging rules and outputs.
   -->
  <targets async="true">
     <target name="console" xsi:type="Console" layout="${longdate} ${level:upperCase=true} ${logger}:${callsite-linenumber} - ${scopeproperty:item=requestId} - ${message}" />
  </targets>
  <rules>
    <!-- Log all events to the json-file target -->
    <logger name="*" writeTo="console" minlevel="Info" />
  </rules>
</nlog>

Here an XML syntax with encoding UTF-8 will be created and followed by NLog tag, which was a basic syntax. Then targets tag is used to specify how we need the logs, whether in a file format, mail or console, or other formats. Inside <target> tag, you need to specify xsi:type="Console" (hereby, I need console logs). Then what layout do you need to specify under the layout property, which describes the details you need inside the logs?

Then follows the rules section. Under this, you need to specify the logger, which has the restriction part, which gives the log level you need, the logger's name, and where to write it.

For this implementation, you must add the relevant dependency package from nuget.org to your ".csproj" file.

<PackageReference Include="NLog.Web.AspNetCore" Version="5.2.1" />

Inside the layout, we have some config renderers,

  1. ${longdate} - used for date time printing when the logs get printed in the sortable format `yyyy-MM-dd HH:mm:ss.ffff`.
  2. ${level:upperCase=true} - used to print by which log level we're logging. I've mentioned the default log levels with their precedence (if set minimum level, then you mention inside the rules under logger tag set property min level = "info" then greater than info-2 (Warning-3, Error-4, Critical-5 )and info-2 logs are getting caught, Debug and Trace won't) below
    public enum LogLevel {
        Trace = 0,
            Debug = 1,
            Information = 2,
            Warning = 3,
            Error = 4,
            Critical = 5,
            None = 6
    }
  3. ${logger} - Name of the logger, the class name in most common cases.

  4. ${callsite-linenumber} - which gives the line number where the log gets jumped out (Error case like a try-catch exception) and prints the log statement where it is held up.

  5. ${scopeproperty:item=requestId} - which is of dynamic value assignment for user convenience like context headers or request-based information. Then you can assign the values inside the code (Earlier MDC, MDLC, NDC, and NDLCs were used but not in the current version. They were put up in a single one).

  6. ${message} - For log messages.

I'm declaring the logger like this in my class for the basic declaration of the logger.

private static Logger logger = LogManager.GetLogger("WeatherForecastController");

By using this logger, you can access the different methods. Here I'm mentioning the info log.

logger.Info("Inside GetWeatherForecast Controller");

Earlier, I said that scope property is a dynamic one. You can set it on your own, which can be set as,

ScopeContext.PushProperty("requestId",1001);

Implementation of NLog with Dotnet6 WebApi

Finally, when running this project

PS C:\Users\admin\Desktop\Logging> dotnet run
Building...
info: Microsoft.Hosting.Lifetime[14]
Now listening on: https://localhost:7052
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5069
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: C:\Users\admin\Desktop\Logging\
2023-01-26 18:09:06.2403 INFO WeatherForecastController:27 - 1001 - Inside GetWeatherForecast Controller

Console log matches the exact layout which we're mentioned "

2023-01-26 18:09:06.2403 (longdate)

INFO (loglevel)

WeatherForecastController: (logger)

27 - (callsite-linenumber)

1001 (scopeproperty:item = requestId)

- Inside GetWeatherForecast Controller" (message)

If you have any doubts & need any guidance, feel free to ask.

Have a great day :) !!!!!!!!