⌘BABAKOV.NET Let's code!
100% [dark] [ru]

Adding Logging to .NET Core Web Application with NLog

Example of adding logging to a Web application on .NET Core based on NLog.

Initially, add the Nuget package:

NLog.Web.AspNetCore

Add a nlog.config file to the project root with the following content:

<?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"
      internalLogLevel="info"
      internalLogFile="internal-nlog.txt">

    <!-- enable asp.net core layout renderers -->
    <extensions>
        <add assembly="NLog.Web.AspNetCore"/>
    </extensions>

    <!-- the targets to write to -->
    <targets>
        <!-- write logs to file  -->
        <target xsi:type="File" name="allfile" fileName="logs/nlog-all-${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />

        <!-- another file log, only own logs. Uses some ASP.NET core renderers -->
        <target xsi:type="File" name="ownFile-web" fileName="logs/nlog-own-${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
    </targets>

    <!-- rules to map from logger name to target -->
    <rules>
        <!--All logs, including from Microsoft-->
        <logger name="*" minlevel="Trace" writeTo="allfile" />

        <!--Skip non-critical Microsoft logs and so log only own logs-->
        <logger name="Microsoft.*" maxLevel="Info" final="true" />
        <!-- BlackHole without writeTo -->
        <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
    </rules>
</nlog>

The file contains logging settings, where and how to save. It is necessary to set the Copy to output directory: Copy Always property for this file.

Now, let's move on to the project settings.

Add the logger object to Program.cs:

public static NLog.Logger Logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();

Don't forget to connect the library in Program.cs:

using NLog.Web;

And again, in Program.cs, redirect logging in the CreateWebHostBuilder method:

.ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                })
                .UseNLog()  // Подключаем NLog

Example of the Program.cs file in its entirety:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Web;

namespace JQueryPostRequestNetCore
{
    public class Program
    {
        public static NLog.Logger Logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
        
        public static void Main(string[] args)
        {
            Logger.Debug("Запуск приложения");

            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
                })
                .UseNLog()  // Подключаем NLog
                .UseUrls("http://localhost:5000");
    }
}

Now, after all manipulations, logging will occur through NLog, taking into account the settings from nlog.config, in our example above, in 2 files.

You can now record your own messages in the application code in LOG as follows:

Program.Logger.Info("Информационное сообщение");
Program.Logger.Warn("Предупреждающее сообщение");
Program.Logger.Error("Сообщение об ошибке");

Of course, all standard events for the logging mode set in appsettings.json will also be recorded.

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

That's it.

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.