NLog使用(2)

发布时间 2023-12-21 09:04:08作者: 落花流水1173

.Net没有内置的文本日志提供者,第三方有Log4Net、NLog、Serilog等,这篇文章主要讲解Nlog使用

Nlog github链接

1、安装Nuget包:NLog

2、配置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">

    <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>

关于这个文档,主要需要配置的地方有:

target:目标,作用是配置目标的类型Type,如File、Console,数据库等,也就是说日志输出到哪里

Layout:日志的格式,如果没设置,会使用默认的格式如下:

<target name="logfile" xsi:type="File" fileName="file.txt" layout="`${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}`" />

对于target和Layout都可以通过官方文档查看

3、使用nlog进行日志记录

internal  class Program
{
    private static readonly Logger logger = LogManager.GetCurrentClassLogger();
    static void Main(string[] args)
    {
        logger.Trace("Hello world");
    }
}

输出如下:

 运行目录下会创建一个"file"文件,并记录日志