在 .NET 記錄 Log 的三種做法,從內建的 ILogger、寫成實體檔案的 NLog,到用 Grafana 檢視。
ILogger(原生)
前置作業 - 註冊:
services.AddLogging(builder =>
{
builder.AddConfiguration(Configuration.GetSection("Logging"))
.AddFilter("Microsoft", LogLevel.Warning)//篩選掉Microsoft.* 的Log
.AddConsole()
.AddDebug();
});
前置作業 - appsetting.json
實作:
_logger.LogDebug("Hi there");
_logger.LogInformation("Hi there");
_logger.LogWarning("Hi there");
_logger.LogError("Hi there");
_logger.LogCritical("Hi there");
備註:會寫到事件檢視器中。
NLog 寫實體檔案
前置作業 - 安裝 Package:
- NLog
- NLog.Extensions.Logging
- NLog.Web.AspNerCore(.Net Core 開發)
前置作業 - 建立 Config,在網站根目錄新增 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' throwExceptions='true' internalLogLevel='Warning' internalLogFile='C:/NLog/nlog-internal.log'>
<!--設定變數-->
<variable name='LogTxtMainPath' value='${basedir}/Logs'/>
<targets>
<!--宣告 Target, 命名為 ErorrFile, 輸出目標 xsi:type -> file, log 檔案名稱 : error.log -->
<target name='ErrorFile' xsi:type='File' fileName='${LogTxtMainPath}/${shortdate}_error.log' layout='${date} | ${uppercase:${level}} | ${counter} ${message} | ${newline}' encoding='utf-8' />
<!--宣告 Target, 命名為 FatalFile, 輸出目標 xsi:type -> file, log 檔案名稱 : error.log -->
<target name='WarnFile' xsi:type='File' fileName='${LogTxtMainPath}/${shortdate}_warn.log' layout='${date} ${message}' />
<!--宣告 Target, 命名為 ErorrFile, 輸出目標 xsi:type -> file, log 檔案名稱 : error.log -->
<target name='Console' xsi:type='Console' />
</targets>
<rules>
<!--微軟錯誤等級:Trace、Debug、Information、Warning、Error、Critical-->
<!--NLog錯誤等級:Trace、Debug、Info、Warn、Error、Fatal-->
<!--加了這一行可以將 Microsoft namespace 下所有 class 產生的 log 過濾掉-->
<logger name='Microsoft.*' minlevel ='Trace' final='true'/>
<!--將所有 class 產生的 Error level 以上的log 根據 'ErrorFile Target' 的設定輸出-->
<logger name='*' minlevel='Error' writeTo='ErrorFile' />
<!--將 NLogPractice namespace 下所有 class 產生的 Debug level log 根據 'Console Target' 的設定輸出-->
<logger name='LogTestProj.HomeController' level='Warning' writeTo='WarnFile' />
<!--將 NLogPractice namespace 下所有 class 產生的 Trace level log 根據 'Console Target' 的設定輸出-->
<logger name='LogTestProj.*' level='Trace' writeTo='Console' />
</rules>
</nlog>
前置作業 - 註冊:
services.AddLogging(logging =>
{
//清除原本的 logging provider(更換 Logging Provider)
logging.ClearProviders();
//設定 logging 的 minmum level 為 trace
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
//使用 NLog 作為 logging provider
logging.AddNLog();
});
實作:
_logger.LogDebug("Hi there");
_logger.LogInformation("Hi there");
_logger.LogWarning("Hi there");
_logger.LogError("Hi there");
_logger.LogCritical("Hi there");
Grafana
UI Server:
docker run -d --name grafana -p 3000:3000 -e GF_SECURITY_ADMIN_USER=admin -e GF_SECURITY_ADMIN_PASSWORD=strongpassword -e TZ=Asia/Taipei grafana/grafana
Log Collection:
程式端使用套件: