.NET 6 配置使用NLog日志框架的方法及示例代码

NLog是一个流行的开源日志记录框架,用于在.NET应用程序中记录日志。它提供了强大的日志记录功能,具有灵活的配置选项和多种目标,可将日志记录到不同的输出位置,例如文件、数据库、控制台等。本文主要介绍.NET 6 中配置使用NLog,以及相关示例代码。

1、安装引用NLog

使用NLog需要安装引用NLog.Extensions.Hosting,如配置文件使用类似 ${aspnet-request-url} 的配置,以aspnet-开头的则需要安装 NLog.Web.AspNetCore。

1)NLog.Extensions.Hosting

在Nuget管理程序中,搜索 "NLog.Extensions.Logging",然后点击安装。

2)NLog.Web.AspNetCore

在Nuget管理程序中,搜索 "NLog.Web.AspNetCore",然后点击安装。

相关文档VS(Visual Studio)中Nuget的使用

2、NLog 配置文件

NLog 中配置文件可以使用XML和JSONSON格式的, 具体如下,

1)XML格式的配置

<?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"
      internalLogLevel="Info"
      internalLogFile="${currentdir}/Logs/error.txt" >

  <!-- enable asp.net core layout renderers -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>
  <!-- the targets to write to -->
  <targets>
    <!-- File Target for all log messages with basic details -->
    <target xsi:type="File" name="allfile" fileName="${currentdir}/Logs/${shortdate}/${level}/${level}.txt" maxArchiveFiles="30"  enableArchiveFileCompression="true"
          concurrentWrites="true"
          keepFileOpen="true"
            layout="${longdate}|${event-properties:item=EventId:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}" />

    <!-- File Target for own log messages with extra web details using some ASP.NET core renderers -->
    <target xsi:type="File" name="ownFile-web" fileName="${currentdir}/Logs/${shortdate}/${level}/web.txt" maxArchiveFiles="30"
            layout="${longdate}|${event-properties:item=EventId:whenEmpty=0}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />

    <!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection -->
    <target xsi:type="Console" name="lifetimeConsole" layout="${MicrosoftConsoleLayout}" />

  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Error" writeTo="allfile" />

    <!--Output hosting lifetime messages to console target for faster startup detection -->
    <logger name="Microsoft.Hosting.Lifetime" minlevel="Info" writeTo="lifetimeConsole, ownFile-web" final="true" />

    <!--Skip non-critical Microsoft logs and so log only own logs (BlackHole) -->
    <logger name="Microsoft.*" maxlevel="Info" final="true" />
    <logger name="System.Net.Http.*" maxlevel="Info" final="true" />

    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>

2)JSON配置文件

"NLog":{
    "internalLogLevel":"Info",
    "internalLogFile":"${currentdir}/Logs/error.log",
    "extensions": [
      { "assembly": "NLog.Extensions.Logging" },
      { "assembly": "NLog.Web.AspNetCore" }
    ],
    "targets":{
        "allfile":{
            "type":"File",
            "fileName":"${currentdir}/Logs/${shortdate}/${level}/${level}.log",
            "layout":"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"
        },
        "ownFile-web":{
            "type":"File",
            "fileName":"${currentdir}/Logs/${shortdate}/${level}/${level}.log",
            "layout":"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}"
        }
    },
    "rules":[
        {
            "logger":"*",
            "minLevel":"Trace",
            "writeTo":"allfile"
        },
        {
            "logger":"Microsoft.*",
            "maxLevel":"Info",
            "final":"true"
        },
        {
            "logger":"*",
            "minLevel":"Trace",
            "writeTo":"ownFile-web"
        }
    ]
}

3、NLog配置及使用示例

参考文档:.NET 6 配置使用NLog日志框架的方法及示例代码-CJavaPy

posted @ 2024-01-06 21:08  leviliang  阅读(168)  评论(0编辑  收藏  举报