首页 > 其他分享 >NLog使用

NLog使用

时间:2023-05-23 19:44:05浏览次数:40  
标签:RichTextBox NLog 使用 组件 日志 logger Logger

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>

标签:RichTextBox,NLog,使用,组件,日志,logger,Logger
From: https://www.cnblogs.com/harrychinese/p/nlog.html

相关文章

  • C# 读取网络上下行(不要使用性能计数器的方式)
    C#读取网络上下行有多种方式,其中有一种是使用System.Net.NetworkInformation命名空间中的NetworkInterface类和PerformanceCounter类,该方式其实读的是windows系统的性能计数器中的NetworkInterface类别的数据。方式如下:NetworkInterfacenetworkInterface=NetworkInterface......
  • 记录--使用率比较低的10个Web API
    这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助avaScript中有些API可能使用率比较低,下面我们逐一介绍它们的用法和使用场景。至于标题,主要是想让你进来看看,兄弟们别打我!BlobAPIBlobAPI用于处理二进制数据,可以方便地将数据转换为Blob对象或从Blob对象读取数......
  • mac docker compose简单使用说明
    1dockercompose简介Compose是Docker的服务编排工具,主要用来构建基于Docker的复杂应用Compose通过一个配置文件来管理多个-Docker容器,非常适合组合使用多个容器进行开发的场景。docker-compose是编排容器的。例如,你有一个php镜像,一个mysql镜像,一个nginx镜像。如果没......
  • mac的截图及sips使用心得
    1-mac推荐截图工具从ubuntu切换到Mac,最放不下手的其实是一个叫flameshot的截图工具,确实是ubuntu系统的神器,但是渐渐熟悉mac后发现mac才是各种大杀器的集合地,今天想谈到的就是截图工具,初接触mac的时候,几乎接触了mac大多数别人推荐的截图工具,如下所示:系统截图工具;微信截图工具;浏览器......
  • Day01-Typora工具使用
    Markdown学习二级标题三级标题四级标题 字体helloworldhelloworldhelloworldhelloworld 引用学习java第一天 分割线 图片 超链接点击跳转到小兔子的博客 列表ABCABC 表格快捷键⌘+⌥+T姓名性别年纪张......
  • .Net使用HttpClient以multipart/form-data形式post上传文件及其相关参数
    httpClient模仿Postman的form-data格式 api接口[HttpPost(Name="/Test/FileTest")]publicJGResponse<PutFileByNameResponse>FileTest([FromForm]PutFileByNameRequestrequestDto){varcapthch=GetCaptcha();......
  • APlayer & MetingJS 音乐播放器使用指南
    1.介绍APlayer是一个简洁漂亮、功能强大的Html5音乐播放器,GitHub地址:https://github.com/DIYgod/APlayerMetingJS是为APlayer添加网易云、QQ音乐等支持的插件,GitHub地址: https://github.com/metowolf/MetingJS2.安装引用三个文件APlayer.min.js  APlayer.min.css ......
  • 使用n对Mac上的Node版本进行管理及升降
    n如果在我的电脑上已经安装了nodejs,但是觉得这个版本不好用,或者是不兼容公司的项目,那么可以使用n进行node的版本管理。n相对于nvm来说,安装起来还是非常方便的。安装1.首先确定nodejs版本,确定已安装nodejsnode-v2.清除nodejs的缓存sudonpmcacheclean-f3.使用npm全......
  • C++ 模板 使用 enum 代替 typename
    enumtestEnum{A,B,C};template<testEnumC>classTestClassTemplate{public:voidprint(){printf("common\n");}};template<>classTestClassTemplate<A>{public:voidprint(){printf(&quo......
  • laradock的基础使用
    一、安装laradock1.如果有laravel项目并使用git,可以用gitsubmodule将laradock克隆到laravel根目录,方便后续管理gitsubmoduleaddhttps://github.com/laradock/laradock.git2.如果不需要安装到gitsubmodule中,可以安装到任意位置gitclonehttps://github.com/laradock/la......