NLog是適用於各類.NET平臺(包括.NET標準)的靈活,免費的日誌記錄平臺,NLog可將日誌寫入多個目標,好比Database、File、Console、Mail。下面介紹下NLog的基本使用方法。git
安裝NLog Nuget package:Install-Package NLog.Config
;github
<?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> <!-- 輸出到文件 --> <target name="logfile" xsi:type="File" fileName="file.txt" /> <!-- 輸出到控制檯 --> <target name="logconsole" xsi:type="Console" /> </targets> <!-- 定義輸出規則,可配置多個 --> <rules> <logger name="*" minlevel="Info" writeTo="logconsole" /> <logger name="*" minlevel="Debug" writeTo="logfile" /> </rules> </nlog>
public class Log { // ... private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); }
以下配置爲本人經常使用配置,可參考該配置及GitHub指導文檔自定義配置:async
注意:首次使用NLog時,可先將throwExceptions
置爲true,這樣若是配置有問題沒有成功打印日誌,VS會拋出異常,方便定位緣由。調試好後,再將該項置爲false。調試
另外:示例中fileName(日誌文件全路徑名稱)是經過後臺代碼配置的,這樣能夠動態設置日誌的輸出位置。日誌
// 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="false" autoReload="true" async="true" encoding="UTF-8"> <targets> <target name="logconsole" xsi:type="Console" layout="${date:format=HH\:mm\:ss} | ${level:padding=-5} | ${message}"/> <target name="logfile" xsi:type="File" createDirs="true" keepFileOpen="true" fileName="${gdc:logDirectory:whenEmpty=${baseDir}}/logs/${shortdate}/Whiteboard.log" archiveFileName="${gdc:logDirectory:whenEmpty=${baseDir}/logs/${shortdate}}/Whiteboard_{##}.log" archiveAboveSize="102400" archiveNumbering="Sequence" maxArchiveDays="30" layout="${longdate} | ${level:uppercase=false:padding=-5} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}"/> </targets> <rules> <logger name="*" minlevel="Debug" writeTo="logconsole"/> <logger name="*" minlevel="Debug" writeTo="logfile" /> </rules> </nlog> // Log.cs 設置日誌文件輸出位置 string logDir = Path.Combine(Environment.GetFolderPath( Environment.SpecialFolder.LocalApplicationData), Process.GetCurrentProcess().ProcessName); NLog.GlobalDiagnosticsContext.Set("logDirectory", logDir);