NLog-manual

本文最后更新于:2024年8月18日 上午

NLog

什么事NLog?

一个开源的.NET日志程序

Getting Start!

可以从NLog的Github仓库处下载源码,或者直接使用NuGet安装到项目中。

Configuration

NLog Configuration file
只有在对NLog进行了配置的情况下,NLog才会输出日志文件。NLog的配置文件用XML的形式进行编写;当然也可以直接在代码中对NLog进行配置。
个人喜欢直接在应用的目录下直接创建NLog.config文件来对NLog进行配置。一个简易的配置文件示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?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"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

<variable name="STDLayout" value="${longdate} | [${level:uppercase=true}] | [${threadid}] | [${callsite}]${newline}[${event-properties:item=caller}]${newline}${message}${newline}${exception:format=ToString}${newline}"/>
<variable name="BasePath" value="${basedir}/Logs/"/>
<variable name="STDPath" value="${BasePath}/STD/Cur_${level:uppercase=true}.log"/>
<variable name="ArchivePath" value="${BasePath}/STD/${level:uppercase=true}_{#}.log"/>
<variable name="ArchiveSize" value ="5242880"/>

<targets async="true">
<target name="STDFile" xsi:type="File" fileName="${STDPath}" layout="${STDLayout}"
archiveFileName="${ArchivePath}"
archiveAboveSize="${ArchiveSize}"
archiveNumbering ="DateAndSequence"
archiveEvery="Hour"
archiveDateFormat ="yyyy-MM-dd-HH"
maxArchiveDays="7"
encoding="utf-8"
/>
</targets>

<rules>
<logger name="webservice*" levels="Trace,Debug,Warn,Error,Fatal" writeTo="STDFile"/>
</rules>
</nlog>

variable标签用于声明变量,这样可以重复使用。target标签就是配置输出目标。logger标签配置输出规则,其name属性很重要,程序中就是通过这个属性值来对logger进行匹配,从而根据再writeTo属性找到target(输出)。
layout是一个很重要的属性,决定了每条日志输出的格式,而像上面的layout中的${longdate}${threadid}等插值,是layout renderer,可以理解成“预设值”,更多“预设值”可以参考官网的layout-renderers页面。
然后是一个简单的程序示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
namespace Learning1
{
public class NLogTest
{
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();

public static void Main()
{
try
{
Logger.Info("Hello world");
throw new Exception("Throw an exception by manual.");
}
catch (Exception ex)
{
Logger.Error(ex, "Goodbye cruel world");
System.Console.ReadKey();
}
}
}
}

这里有一只爱丽丝

希望本文章能够帮到您~


NLog-manual
https://map1e-g.github.io/2024/05/09/NLog-manual/
作者
MaP1e-G
发布于
2024年5月9日
许可协议