NLog使用

发布时间 2023-05-23 19:41:48作者: harrychinese

Nlog 日志组件的使用

这个博文关注 .net framework下的NLog日志组件的使用. 在项目中需要将日志写到日志文件中, 另外一些重要信息要显示在界面上. 使用 NLog 可以轻松做到这点.
NLog wiki 页面

nuget 安装两个主要组件

  • NLog
  • NLog.Windows.Forms

使用总结

  1. 日志文件 layout 按照 json 结构化的格式输出, 方便以后分析
  2. 两个 RichTextBox 用来显示日志. 一个用来显示较多的日志, 设置行数为 2000; 另一个用来显示最新的日志, 显示最近3行, 日志格式也有详略不同, 使用 NLog 可以很容易做到行数控制, 另外还提供 error 高亮显示.
  3. RichTextBox 日志target 中的 formName 和 controlName 必须和Winform designer上的名称完全一致, 包括大小写. 另外, RichTextBox 组件所在窗体的 logger 成员变量不应该在声明变量的时候就完成初始化, 而应该在窗体 Load 事件中完成初始化, 这样能确保窗体实例化发生在 logger 实例化之前, NLog.Windows.Forms 组件才能正常工作, 否则 RichTextBox 无法正常输出日志.

Logger 的初始化代码

// private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); //不能直接初始化
private static readonly NLog.Logger Logger =null ; 

private void Form1_Load(object sender, EventArgs e)
{
    if (_logger == null)
    {
        _logger = NLog.LogManager.GetCurrentClassLogger();
    }
}

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"
      autoReload="true"
      throwConfigExceptions="true">

	<targets async="true">
		<!--此部分中的所有目标将自动异步-->

		<!--项目日志保存文件路径说明fileName="${basedir}/保存目录,以年月日的格式创建/${shortdate}/${记录器名称}-${单级记录}-${shortdate}.txt"-->
		<target name="file" xsi:type="File"
                fileName="${basedir}/logs/${shortdate}/${processname}-${shortdate}.txt"
                concurrentWrites="true"
                keepFileOpen="false"
                encoding="utf-8">
			<layout xsi:type="JsonLayout">
				<attribute name="time" layout="${longdate}" />
				<attribute name="level" layout="${level:uppercase=true}" />
				<attribute name="threadname" layout="${threadname}" />
				<attribute name="message" layout="${message}" />
				<attribute name="properties" encode="false">
					<layout type='JsonLayout' includeEventProperties="true" maxRecursionLimit="2" />
				</attribute>
				<attribute name='exception' layout='${exception:format=ToString,StackTrace}' />
			</layout>
		</target>

		<!--在主界面的 richTextBox 中显示日志-->
		<target  name="logRichbox" xsi:type="RichTextBox"
          layout="${time} ${level:uppercase=true} [${threadname}] ${message} ${onexception:${exception:format=Message}}"
          autoScroll="true"
          maxLines="2000"
          formName="FrmMain"
          controlName="logRichbox"
          useDefaultRowColoringRules="true" />

		<!--在主界面的 richTextBox 中显示日志-->
		<target  name="singleLineLogRichbox" xsi:type="RichTextBox"
          layout="${level:uppercase=true}  ${message} ${onexception:${exception:format=Message}}"
          autoScroll="true"
          maxLines="2"
          formName="FrmMain"
          controlName="singleLineLogRichbox"
          useDefaultRowColoringRules="true" />
	</targets>

	<!--规则配置-->
	<rules>
		<logger name="*" minlevel="Info" writeTo="file,logRichbox,singleLineLogRichbox" />
	</rules>
</nlog>