昨天有提到 ASP.NET Core 框架提供的 logging API 對第三方的日誌紀錄框架有很高的支援度。過去我都是使用 NLog 為主,所以今天就來看看怎麼在 ASP.NET Core 網站中使用這個框架吧~
Install-Package NLog -Version 4.5.10
Install-Package NLog.Web.AspNetCore -Version 4.7.0
dotnet add package NLog --version 4.5.10
dotnet add package NLog.Web.AspNetCore --version 4.7.0
詳細文件可以參考官方維基,我自己習慣把不同等級的訊息寫到不同檔案內,NLog 設定檔會長這樣:
<?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"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!--
See https://github.com/nlog/nlog/wiki/Configuration-file
for information on customizing logging rules and outputs.
-->
<targets>
<!--
add your targets here
See https://github.com/nlog/NLog/wiki/Targets for possible targets.
See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
-->
<target xsi:type="File" name="debug-files" fileName="${basedir}/logs/debug-${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
<target xsi:type="File" name="info-files" fileName="${basedir}/logs/info-${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
<target xsi:type="File" name="error-files" fileName="${basedir}/logs/error-${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
</targets>
<rules>
<!-- add your logging rules here -->
<logger name="*" level="Debug" writeTo="debug-files" />
<logger name="*" levels="Info,Warn" writeTo="info-files" />
<logger name="*" minlevel="Error" writeTo="error-files" />
</rules>
</nlog>
確認檔案屬性,「進階 > 複製到輸出目錄 > 有更新時才複製」,確保建置時會把檔案複製到執行目錄。
修改 CreateWebHostBuilder
中設定日誌提供者的地方:
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
var startupAssemblyName = typeof(Startup).GetTypeInfo().Assembly.FullName;
return WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((hostContext, loggingBuilder) =>
{
loggingBuilder.ClearProviders();
})
.UseNLog()
.UseStartup(startupAssemblyName);
}
以上就完成基本 NLog 的設定,注入 ILogger
跟 _logger.Log{LogLevel}
的方式都跟昨天一樣,這是因為 ASP.NET Core 提供統一的 logging API。呼叫請求後,可以在執行路徑裡面看到日誌檔案,內容會包括:
2018-10-29 17:44:58.8670 WARN Log Information in LoggerController