优势
上手简单,文档比 log4net 更友好,快速解决了 DLL log 的问题。
简介
Flexible & free open-source logging for .NET
资源:
- github
- NLog 项目官网
- 官方教程
-
使用技巧
写入至多个位置
参考官方教程同时写入 file.txt 和控制台:
<?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>
滚动写入 Archive
NLog 没有明显和滚动写入相关的配置,这是因为它通过更强大的 Archive(归档) 实现了滚动写入及更多功能。
4.5 及以上版本有个很好的官方示例 Archive old log files。
它实现以下几个功能:
- 每天首次写入日志时新建一个 log 文件
- 若当天的 log 文件大于 10240B 就分隔 log 文件
保留之前 3 天的所有 log 文件,更老的就自动删掉
<?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}/logs/logfile.txt"maxArchiveFiles="4"archiveAboveSize="10240"archiveEvery="Day" /></targets><rules><logger name="*" minlevel="Debug" writeTo="file" /></rules></nlog>
自动创建的 log 文件名如下:
* logfile.txt* logfile.3.txt* logfile.2.txt* logfile.1.txt
4.5 以下的老版本可以参考 FileTarget Archive Examples 中的诸多例子实现滚动写入。
同一解决方案的多个项目使用一套 NLog 配置
- 在启动项目安装 NLog
- 在启动项目中配置 NLog.config
- 在其他项目安装 NLog
- 删除其他项目中的 NLog.config 和 NLog.xsd 文件
通过 RictTextBox 输出 Log 信息
WinForm
先安装 NLog 和 NLog.Windows.Forms,再参考 配置说明 配置 NLog.config。
两种输出方式:
- NLog 自动创建一个包含 RichTextBox 的 Form(默认)
- 输出到已有 Form 的 RichTextBox
要想输出到已有 Form,有三个关键点:
- 保证 NLog config 中的 formName=”FormMain” controlName=”rtbLog” 和实际用的一致
- NLog config 中设置
allowAccessoryFormCreation="False" - 在 Form 初始化控件完毕后插入这句代码
RichTextBoxTarget.ReInitializeAllTextboxes(this);
设置输出样式,可以参考 SOF。
示例:将 Trace 级别的日志输出到窗体名为 FormMain 中的一个名为 RtbLog 的 RichTextBox 中。
<targets async="true"><target xsi:type="RichTextBox" name="LogRtb"layout="${time} ${message}" maxLines="500"height="200" width="600" autoScroll="True" supportLinks="False" toolWindow="True"formName="FormMain" controlName="rtbLog" allowAccessoryFormCreation="False" ><row-coloring condition="level == LogLevel.Trace" fontColor="Gray" backgroundColor="Control" /><row-coloring condition="level == LogLevel.Info" fontColor="ControlText" backgroundColor="Control" /></target></targets><rules><!-- LogRtb just log trace and info --><logger name="*" level="Trace" writeTo="LogRtb"/></rules>
注:设置 row-coloring 是为了分辨输出的日志级别。
WPF
参考前人做好的轮子:https://github.com/erizet/NlogViewer
