.Net Core 使用NLog

  之前.Net Framework時使用的NLog,到了.Net Core後,使用方式有點不同,整理如下。

加入套件
  • NLog
  • NLog.Web.AspNetCore

新增NLog.config檔案
設定檔已針對Microsoft及Hosting等略過及Conosle處理
<?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" throwExceptions="false"
      xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <extensions>
    <add assembly="Microsoft.ApplicationInsights.NLogTarget" />
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>
  <variable name="layoutDefine"
      value="${longdate} [${event-properties:item=EventId_Id:whenEmpty=0}][${level:padding=-5}] ${message} ${exception:format=tostring} (${callsite:includeNamespace=false:fileName=true:includeSourcePath=false})" />
  <targets>
    <!---預設所有資訊先寫到Trace-->
    <target xsi:type="Trace" name="TraceOutput" rawWrite="true" layout="${layoutDefine}" />
    <!---寫到Console-->
    <target xsi:type="Console" name="lifetimeConsole" layout="${MicrosoftConsoleLayout}" />
   
    <!--寫入檔案-->
    <target name="NLogFile" xsi:type="File"
    layout="${longdate}-[${level}]-${logger}:${message} ${exception:format=tostring}"
    fileName="${aspnet-appbasepath}\wwwroot\Logs\current_.log"
    archiveFileName="${aspnet-appbasepath}\wwwroot\Logs\{#}_.log"
    maxArchiveFiles="10" encoding="utf-8" archiveDateFormat="yyyyMMdd" archiveNumbering="Date" archiveEvery="Day"
        />
    <!--寫入Application Insights-->
    <!--<target type="ApplicationInsightsTarget" name="aiTarget" />-->
  </targets>
  <rules>
    <!---預設所有資訊先寫到Trace-->
    <logger name="*" writeTo="TraceOutput" />
    <!--Host資訊寫到Console -->
    <logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole" final="true" />
    <!--略過微軟及Http相關資訊,避免寫入下方的NLogFile -->
    <logger name="Microsoft.*" maxlevel="Info" final="true" />
    <logger name="System.Net.Http.*" maxlevel="Info" final="true" />
    <logger name="*" minlevel="Info" writeTo="NLogFile" />
  </rules>
</nlog>

程式引用NLog
builder.Logging.ClearProviders();//先清除原本的Log提供者
builder.WebHost.UseNLog();
預設會自行引用NLog.config

測試輸出
使用.Net Core Web Page
public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }
        public void OnGet()
        {
            _logger.LogTrace("1.Trace");
            _logger.LogDebug("2.Debug");
            _logger.LogInformation("3.Information");
            _logger.LogWarning("4.Warning");
            _logger.LogError("5.Error");
            _logger.LogCritical("6.Critical");
        }
    }

針對NLog.config的設定,預設所有資訊會輸到的debug視窗
Microsoft.Hosting.Lifetime  輸出到Console

使用Loggger 輸出到檔案,設定層級為Info
檔案位置: wwwroot\Logs
2022-11-17 11:32:46.2017-[Info]-NetCoreWebNlog.Pages.IndexModel:3.Information
2022-11-17 11:32:46.2017-[Warn]-NetCoreWebNlog.Pages.IndexModel:4.Warning
2022-11-17 11:32:46.2017-[Error]-NetCoreWebNlog.Pages.IndexModel:5.Error
2022-11-17 11:32:46.2017-[Fatal]-NetCoreWebNlog.Pages.IndexModel:6.Critical

整合AppSetting的Logging 區段
到目前為止的記錄層級,使用的是在NLog.config所定義好的,正式上線時,我們會透過appsettings.json來區分環境,若只使用NLog.config會比較難切分。
此時我們可以將appsetting.json的Logging來調整NLog.config的層級,如下圖兩邊對應,ps: 左邊的Default = 右邊的*
對應好,Program.cs 需再調整才會生效
//原 builder.WebHost.UseNLog();
//改
builder.WebHost.UseNLog(new NLogAspNetCoreOptions() { RemoveLoggerFactoryFilter = false });

補充:若不使用Logging區段,也可以使用將整個NLog,config搬到appsettings.json,本文沒有實作,需要的話可以參考官方範例

其它/參考

這個網誌中的熱門文章

IIS 設定只允許特定IP進入