一:简介
NLog是一个简单灵活的.NET日志记录类库。通过使用NLog,我们可以在任何一种.NET语言中输出带有上下文的(contextual information)调试诊断信息,根据喜好配置其表现样式之后发送到一个或多个输出目标(target)中。
详细配置文章请参考:http://www.cnblogs.com/RitchieChen/archive/2012/07/16/2594308.html
二:应用
直接在NuGet中下载Nlog包即可,需要在项目的根目录下创建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}" fileName="${basedir}/logs/${level}.txt" //level是已文件级别作为日志名,shortdate是以时间作为日志名
keepFileOpen="false" /> </targets> <rules> <logger name="*" minlevel="Debug" writeTo="file" /> </rules> </nlog>
异步写入文件
<?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="AsyncWrapper" queueLimit="5000" overflowAction="Discard"> <target name="file" xsi:type="File" layout="${longdate} ${logger} ${message}" fileName="${basedir}/logs/${level}.txt" keepFileOpen="false" /> </target> </targets> <rules> <logger name="*" minlevel="Debug" writeTo="file" /> </rules> </nlog>
配置语法
<targets> <target xsi:type="File" name="String" layout="Layout" header="Layout" footer="Layout" encoding="Encoding" lineEnding="Enum" archiveAboveSize="Long" maxArchiveFiles="Integer" archiveFileName="Layout" archiveNumbering="Enum" archiveEvery="Enum" replaceFileContentsOnEachWrite="Boolean" fileAttributes="Enum" fileName="Layout" deleteOldFileOnStartup="Boolean" enableFileDelete="Boolean" createDirs="Boolean" concurrentWrites="Boolean" openFileCacheTimeout="Integer" openFileCacheSize="Integer" networkWrites="Boolean" concurrentWriteAttemptDelay="Integer" concurrentWriteAttempts="Integer" bufferSize="Integer" autoFlush="Boolean" keepFileOpen="Boolean" /> </targets>
控制台
class Program { static void Main(string[] args) { NLog.Logger log = NLog.LogManager.GetCurrentClassLogger(); log.Debug("记录一个错误日志"); Console.WriteLine("执行完毕"); Console.ReadKey(); } }