.NET日志框架Nlog使用介绍

2022-04-16 20:47:16
目录
快速安装快速配置快速使用详解配置添加支持Console输出输出至CSV文件配置日志大小配置日志分级配置生成规则日志过滤器条件语言条件函数

NLog是一个基于.NET平台编写的类库,我们可以使用NLog在应用程序中添加极为完善的跟踪调试代码。

NLog是一个简单灵活的.NET日志记录类库。通过使用NLog,我们可以在任何一种.NET语言中输出带有上下文的(contextual information)调试诊断信息,根据喜好配置其表现样式之后发送到一个或多个输出目标(target)中。

快速安装

在软件包管理器控制台中使用GUI或以下命令:

1.安装Nlog

Install-Package Nlog

2.安装Nlog.Config

Install-Package Nlog.Config

快速配置

打开目录中得Nlog.Config文件, 可以注意到, XML文件中有详细说明, rules区允许添加用户自定义得路由规则, targets则用于配置一些输出目标, 如下:

<?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"      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"      autoReload="true"      throwExceptions="false"      internalLogLevel="Off" internalLogFile="c:tempnlog-internal.log">  <!-- optional, add some variables  https://github.com/nlog/NLog/wiki/Configuration-file#variables  -->  <variable name="myvar" value="myvalue"/>  <!--  See https://github.com/nlog/nlog/wiki/Configuration-file  for information on customizing logging rules and outputs.   -->  <targets>    <!--    add your targets here    See https://github.com/nlog/NLog/wiki/Targets for possible targets.    See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.    -->    <!--    Write events to a file with the date in the filename.    <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"            layout="${longdate} ${uppercase:${level}} ${message}" />    -->  </targets>  <rules>    <!-- add your logging rules here -->    <!--    Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"    <logger name="*" minlevel="Debug" writeTo="f" />    -->  </rules></nlog>。

ends-with(s1,s2)确定第二个字符串是否是第一个字符串的后缀。返回:true当第二个字符串是第一个字符串的前缀时,false否则返回。

equals(o1,o2)比较两个对象是否相等。返回:true当两个对象相等时,false否则返回。

length(s) 返回字符串的长度。

starts-with(s1,s2)确定第二个字符串是否是第一个字符串的前缀。返回:true当第二个字符串是第一个字符串的前缀时,false否则返回。

regex-matches(input, pattern, options)在NLog 4.5中引入。指示正则表达式是否pattern在指定的input字符串中找到匹配项。options是一个可选的逗号分隔的RegexOptions枚举值列表。

返回:true当在输入字符串中找到匹配项时,false否则返回。

范例:regex-matches('${message}', '^foo$', 'ignorecase,singleline')

到此这篇关于.NET日志框架Nlog使用介绍的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。