NLog使用
Nlog 日志組件的使用
這個博文關注 .net framework下的NLog日志組件的使用. 在項目中需要將日志寫到日志文件中, 另外一些重要信息要顯示在界面上. 使用 NLog 可以輕松做到這點.
NLog wiki 頁面
nuget 安裝兩個主要組件
- NLog
- NLog.Windows.Forms
使用總結
- 日志文件 layout 按照 json 結構化的格式輸出, 方便以后分析
- 兩個 RichTextBox 用來顯示日志. 一個用來顯示較多的日志, 設置行數為 2000; 另一個用來顯示最新的日志, 顯示最近3行, 日志格式也有詳略不同, 使用 NLog 可以很容易做到行數控制, 另外還提供 error 高亮顯示.
- RichTextBox 日志target 中的 formName 和 controlName 必須和Winform designer上的名稱完全一致, 包括大小寫. 另外, RichTextBox 組件所在窗體的 logger 成員變量不應該在聲明變量的時候就完成初始化, 而應該在窗體 Load 事件中完成初始化, 這樣能確保窗體實例化發生在 logger 實例化之前, NLog.Windows.Forms 組件才能正常工作, 否則 RichTextBox 無法正常輸出日志.
log level
對于 warn 和 error 不太好區分, Nlog 文檔給出了一個很好的區分規則, 如果參數驗證或者是可恢復的臨時失敗記錄為warn就可以了, 如果是功能失敗登記為 error.

Logger 的初始化代碼
// private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); //不能直接初始化
private static readonly NLog.Logger Logger =null ;
private void Form1_Load(object sender, EventArgs e)
{
if (_logger == null)
{
_logger = NLog.LogManager.GetCurrentClassLogger();
}
}
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"
throwConfigExceptions="true">
<targets async="true">
<!--此部分中的所有目標將自動異步-->
<!--項目日志保存文件路徑說明fileName="${basedir}/保存目錄,以年月日的格式創建/${shortdate}/${記錄器名稱}-${單級記錄}-${shortdate}.txt"-->
<target name="file" xsi:type="File"
fileName="${basedir}/logs/${shortdate}/${processname}-${shortdate}.txt"
concurrentWrites="true"
keepFileOpen="false"
encoding="utf-8">
<layout xsi:type="JsonLayout">
<attribute name="time" layout="${longdate}" />
<attribute name="level" layout="${level:uppercase=true}" />
<attribute name="threadname" layout="${threadname}" />
<attribute name="message" layout="${message}" />
<attribute name="properties" encode="false">
<layout type='JsonLayout' includeEventProperties="true" maxRecursionLimit="2" />
</attribute>
<attribute name='exception' layout='${exception:format=ToString,StackTrace}' />
</layout>
</target>
<!--在主界面的 richTextBox 中顯示日志-->
<target name="logRichbox" xsi:type="RichTextBox"
layout="${time} ${level:uppercase=true} [${threadname}] ${message} ${onexception:${exception:format=Message}}"
autoScroll="true"
maxLines="2000"
formName="FrmMain"
controlName="logRichbox"
useDefaultRowColoringRules="true" />
<!--在主界面的 richTextBox 中顯示日志-->
<target name="singleLineLogRichbox" xsi:type="RichTextBox"
layout="${level:uppercase=true} ${message} ${onexception:${exception:format=Message}}"
autoScroll="true"
maxLines="2"
formName="FrmMain"
controlName="singleLineLogRichbox"
useDefaultRowColoringRules="true" />
</targets>
<!--規則配置-->
<rules>
<logger name="*" minlevel="Info" writeTo="file,logRichbox,singleLineLogRichbox" />
</rules>
</nlog>
NLog WithProperty 的妙用
在分布式應用開發中, 我們經常需要在日志中輸出 traceId, 但每次日志輸出, 如果要將 traceId 變量合并日志文本一起輸出, 代碼太難看了. 可以使用 WithProperty 來講traceId加到 logger 屬性中, 在日志的layout中將這個屬性輸出即可.
// WithProperty will return a new unique Logger with the newly added property
var newLogger = logger.WithProperty("traceId", myValue);
newLogger.Info("hello");
newLogger.Info("again"); // will also have "myProperty"
logger.Info("hi"); // is not affected
Nlog.config 可以將日志event所有屬性一起輸出:
layout="${time} ${level:uppercase=true} [${threadname}] ${all-event-properties} ${message} ${onexception:${exception:format=Message}}"
Nlog.config 也可以將日志event指定屬性輸出:
layout="${time} ${level:uppercase=true} [${threadname}] ${event-properties:item=traceId} ${message} ${onexception:${exception:format=Message}}"

浙公網安備 33010602011771號