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);