原文位址:https://www.cnblogs.com/zh7791/p/12620439.html
NLog是一個基于.NET平台編寫的類庫,我們可以使用NLog在應用程式中添加極為完善的跟蹤調試代碼。
NLog是一個簡單靈活的.NET日志記錄類庫。通過使用NLog,我們可以在任何一種.NET語言中輸出帶有上下文的(contextual information)調試診斷資訊,根據喜好配置其表現樣式之後發送到一個或多個輸出目标(target)中。
如果嫌棄字多懶得看, 點選跳轉視訊位址
快速安裝#
在軟體包管理器控制台中使用GUI或以下指令:
1.安裝Nlog
Install-Package Nlog
2.安裝Nlog.Config
Install-Package Nlog.Config
快速配置#
打開目錄中得Nlog.Config檔案, 可以注意到, XML檔案中有詳細說明, rules區允許添加使用者自定義得路由規則, targets則用于配置一些輸出目标, 如下:
<?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">
<!-- optional, add some variables
https://github.com/nlog/NLog/wiki/Configuration-file#variables
-->
<variable name="myvar" value="myvalue"/>
<!--
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.
-->
<!--
Write events to a file with the date in the filename.
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
-->
</targets>
<rules>
<!-- add your logging rules here -->
<!--
Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f"
<logger name="*" minlevel="Debug" writeTo="f" />
-->
</rules>
</nlog>
我們暫時把注釋的說明代碼移除, 還原到最簡潔得XML格式, 如下:
<?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" >
<targets>
<!--這個目标:最終輸出檔案類型, 位于根目錄中得logs檔案夾中, 名稱以每日得時間一次生成log檔案 , layout: 這個選項為生成的格式-->
<target xsi:type="File" name="f"
fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
</targets>
<rules>
<!--設定了一個Debug得路由, 最終指向了一個f名稱得目标 -->
<logger name="*" minlevel="Debug" writeTo="f" />
</rules>
</nlog>
快速使用#
1.建立Nlog執行個體
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
2.使用Debug進行輸出
由于在Nlog.Config當中, 我們已經添加了Debug的最終輸出目标, 是以我們嘗試輸出Debug的内容:
class Program { private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); static void Main(string[] args) { Logger.Debug("我出現了意外!"); Console.ReadKey(); } }
運作完成之後,可以在目前的輸出目錄中, 發生已經生成了一個logs的檔案夾,并且生成了目前電腦日期的log檔案 (這個規則在Nolog.Config當中可以進行配置), 如圖所示:
詳解配置#
關于rules中, 我們可以添加多種路由規則, 并且指向多個目标, 如下所示:
添加支援Console輸出#
1.在rules中添加Info, writeTo指向一個Console的目标
<targets>
<!--<target xsi:type="File" name="f"
fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />-->
<target xsi:type="Console" name="console"/>
</targets>
<rules>
<!--<logger name="*" minlevel="Debug" writeTo="f" />-->
<logger name="*" minlevel="Info" writeTo="console"/>
</rules>
2.使用Info輸出
輸出至CSV檔案#
1.在rules中添加一個新的路由, 以支援csv檔案, 并且添加一個目标, 輸出至csv檔案, column可以用于指定每列生成的資料内容格式
<targets>
<target name="csv" xsi:type="File" fileName="${basedir}/file.csv">
<layout xsi:type="CSVLayout">
<column name="time" layout="${longdate}" />
<column name="message" layout="${message}" />
<column name="logger" layout="${logger}"/>
<column name="level" layout="${level}"/>
</layout>
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="csv" />
</rules>
最終調用Debug("xxxx"), 輸出的效果如下:
配置日志大小#
Nlog允許使用者配置單個檔案大小, 放置在内容過長效率過慢,配置了大小之後, Nlog會自動建立一個新的檔案副本,插入新的日志輸出。
- maxArchiveFiles: 允許生成的副本檔案最大數量
- archiveAboveSize: 允許單個檔案得最大容量
- archiveEvery: 按天生成
- layout: 目前得内容布局格式
- fileName: 包含完整得生成檔案得路徑喝檔案名
<targets>
<target name="file" xsi:type="File"
layout="${longdate} ${logger} ${message}${exception:format=ToString}"
fileName="${basedir}/logs/logfile.txt"
maxArchiveFiles="5"
archiveAboveSize="10240"
archiveEvery="Day" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="file" />
</rules>
配置日志分級#
單個檔案目标可用于一次寫入多個檔案。以下配置将導緻每個日志級别的日志條目被寫入一個單獨的檔案,支援以下格式:
Trace.log
Debug.log
Info.log
Warn.log
Error.log
Fatal.log
隻需要在Nlog.Config中配置以下内容即可:
<?xml version="1.0" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="file" xsi:type="File"
layout="${longdate} ${logger} ${message}${exception:format=ToString}"
fileName="${basedir}/${level}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="file" />
</rules>
</nlog>
配置生成規則#
隻需要将filename中編寫得固定名稱修改程 ${shortdate} 即可
<?xml version="1.0" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="file" xsi:type="File"
layout="${longdate} ${logger} ${message}${exception:format=ToString}"
fileName="${basedir}/${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="file" />
</rules>
</nlog>
日志過濾器#
可以在路由當中, 為每個路由配置自定義得日志過濾器fliter, 如下所示, 示範了使用各種表達式來配置過濾器:
<rules>
<logger name="*" writeTo="file">
<filters>
<when condition="length('${message}') > 100" action="Ignore" />
<when condition="equals('${logger}','MyApps.SomeClass')" action="Ignore" />
<when condition="(level >= LogLevel.Debug and contains('${message}','PleaseDontLogThis')) or level==LogLevel.Warn" action="Ignore" />
<when condition="not starts-with('${message}','PleaseLogThis')" action="Ignore" />
</filters>
</logger>
</rules>
條件語言#
過濾器表達式以特殊的迷你語言編寫。該語言包括:
關系運算符:==,!=,<,<=,>=和>
注意:一些預先定義的XML字元可能需要轉義。例如,如果嘗試使用'<'字元,則XML解析器會将其解釋為開始标記,這會導緻配置檔案中的錯誤。而是<在這種情況下使用轉義版本的<<(())。
布爾運算符:and,or,not
始終被視為布局的字元串文字- ${somerenderer}
布爾文字- true和false
數值文字-例如12345(整數文字)和12345.678(浮點文字)
日志級别文字- LogLevel.Trace,LogLevel.Debug,...LogLevel.Fatal
預定義的關鍵字來通路最常用的日志事件屬性- level,message和logger
花括号-一起覆寫預設優先級和分組表達式
條件函數-執行string和object測試
單引号應與另一個單引号轉義。
條件函數#
以下條件功能可用:
contains(s1,s2)确定第二個字元串是否是第一個的子字元串。傳回:true當第二個字元串是第一個字元串的子字元串時,false否則傳回。
ends-with(s1,s2)确定第二個字元串是否是第一個字元串的字尾。傳回:true當第二個字元串是第一個字元串的字首時,false否則傳回。
equals(o1,o2)比較兩個對象是否相等。傳回:true當兩個對象相等時,false否則傳回。
length(s) 傳回字元串的長度。
starts-with(s1,s2)确定第二個字元串是否是第一個字元串的字首。傳回:true當第二個字元串是第一個字元串的字首時,false否則傳回。
regex-matches(input, pattern, options)在NLog 4.5中引入。訓示正規表達式是否pattern在指定的input字元串中找到比對項。options是一個可選的逗号分隔的RegexOptions枚舉值清單。
傳回:true當在輸入字元串中找到比對項時,false否則傳回。
範例:regex-matches('${message}', '^foo$', 'ignorecase,singleline')
關于更多内容#
通路: https://github.com/NLog/NLog , 檢視更多内容