Un esempio di come usare NLog in un progetto .NET 5

Per prima cosa importare i pacchetti NuGet necessari:
DOS / Batch file
dotnet add package NLog.Web.AspNetCore

Configurazione con appsettings.json

La prima cosa è registrare le dipendenze nel file Program.cs:
C#: Program.cs
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Web;    // NLog

namespace Sgart
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // configurazione NLog su appsettings.json
            var config = new ConfigurationBuilder()
                .SetBasePath(System.IO.Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).Build();
            NLog.LogManager.Configuration = new NLog.Extensions.Logging.NLogLoggingConfiguration(config.GetSection("NLog"));
            var logger = NLog.Web.NLogBuilder.ConfigureNLog(NLog.LogManager.Configuration).GetCurrentClassLogger();

            try
            {
                // scrivo nel log
                logger.Debug("Start main");

                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception exception)
            {
                logger.Error(exception, "Stopped program because of exception");
                throw;
            }
            finally
            {
                // rilascio le risorse usate da NLog
                NLog.LogManager.Shutdown();
            }

        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                // configurazione NLog
                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.SetMinimumLevel(LogLevel.Trace);
                })
                // configurazione dependecny injection NLog
                .UseNLog();
    }
}
Gestisco la configurazione di NLog nel file appsettings.json

poi va configurato il file JSON appsettings.json
JSON: appsettings.json
{
    ...

    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "NLog": {
        "throwConfigExceptions": true,
        "autoReload": true,
        "internalLogLevel": "Info",
        "internalLogFile": "c:/logs/Sgart.it/internal.log",
        "targets": {
            "log-console": {
                "type": "Console"
            },
            "all-file": {
                "type": "File",
                "fileName": "c:/logs/Sgart.it/all-${shortdate}.log",
                "layout": "${longdate} ${uppercase:${level}}| ${message} | ${callsite} ${exception:format=tostring}"

            },
            "log-trace": {
                "type": "Trace"
            }
        },
        "rules": [
            {
                "logger": "*",
                "minLevel": "Trace",
                "writeTo": "log-console"
            },
            {
                "logger": "*",
                "minLevel": "Trace",
                "writeTo": "all-file"
            },
            {
                "logger": "*",
                "minLevel": "Trace",
                "writeTo": "log-trace"
            }
        ]
    }
}

Configurazione con nlog.config

Nel caso si voglia usare il file di configurazione separato nlog.config al posto di appsettings.json, la configurazione è questa:
C#: Program.cs
namespace Sgart
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // configurazione NLog su nlog.config
            var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();

            try {
                // scrivo nel log
                logger.Debug("Start main");

                // il resto è identico
                ...
il relativo file di configurazione sarà in formato XML simile a questo:
XML: 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"
      autoReload="true"
      internalLogLevel="Info"
      internalLogFile="c:\logs\Sgart.it\internal.log">

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

  <!-- the targets to write to -->
  <targets>
    <!-- File Target for all log messages with basic details -->
    <target xsi:type="File" name="allfile" fileName="c:\logs\Sgart.it\all-${shortdate}.log"
            layout="${longdate} ${uppercase:${level}}| ${message} | ${callsite} ${exception:format=tostring}" />

    <!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection -->
    <target xsi:type="Console" name="lifetimeConsole" layout="${level:truncate=4:tolower=true}\: ${logger}[0]${newline}      ${message}${exception:format=tostring}" />
  </targets>

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

    <!--Output hosting lifetime messages to console target for faster startup detection -->
    <logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole" final="true" />

    <!--Skip non-critical Microsoft logs and so log only own logs (BlackHole) -->
    <logger name="Microsoft.*" maxlevel="Info" final="true" />
    <logger name="System.Net.Http.*" maxlevel="Info" final="true" />
  </rules>
</nlog>
Per maggiori info vedi Usare NLog in una console application Net Core 3.1 e NLog.Web
Potrebbe interessarti anche: