[ASP.Net Core] 為.NetCore 3.1應用加上NLog紀錄資訊

為.NetCore 3.1應用加上NLog紀錄資訊

簡單的配置,不過每次要用都要去查文章,不如自己寫一篇


1.install nuget package

dotnet add package NLog.Web.AspNetCore
dotnet add package NLog

2.add Nlog.config,加上一些常用的設定

  • throwConfigExceptions - 設定有錯誤時會拋出exception
  • internalLogToConsole - 將Log輸出到Console視窗
  • archiveAboveSize - 單一檔案的大小限制,超過的拆分檔案
  • archiveNumbering - 拆分的檔名的規則
  • archiveFileName - 拆分的檔名
  • maxArchiveFiles - 拆分的檔案數量上限
<?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"
      throwConfigExceptions="true"
      internalLogToConsole="true"
      internalLogLevel="info">

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

    <variable name="log-root" value="Log" />
    <variable name="log-daily" value="${log-root}/${date:format=yyyy}/${date:format=yyyy-MM}/${shortdate}" />

    <!-- the targets to write to -->
    <targets>
        <target encoding="utf-8" xsi:type="File" name="debug-all"
                fileName="${log-daily}/Debug/${shortdate}[Debug][_all].log"
                archiveAboveSize="20480000"
                archiveNumbering="Sequence"
                archiveFileName="${log-daily}/Debug/${shortdate}[Debug][_all]-{####}.log"
                maxArchiveFiles="2000"
                layout="[${time}][${logger}][${level}] - ${message} ${onexception:inner=${newline}${exception:format=ToString}}" />
    </targets>

    <!-- rules to map from logger name to target -->
    <rules>
        <logger name="*" minlevel="Debug" writeTo="debug-all" />
    </rules>
</nlog>

3.調整Program.cs,設定config以及註冊NLog

        public static void Main(string[] args)
        {
            var logger = NLogBuilder.ConfigureNLog("NLog.config").GetCurrentClassLogger();
            try
            {
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Get Error.");
                throw;
            }
            finally
            {
                NLog.LogManager.Shutdown();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>()
                              .UseNLog();
                }); 

4.接著只要在需要的地方注入 ILogger<T>或是ILoggerFactory來紀錄log即可


Nlog GitHub https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-3

Sample Code https://github.com/ianChen806/NLogSample