NLog文档说明了如何使用nlog.config XML文件为.NET Core应用程序配置NLog。但是,我希望我的应用程序只有一个配置文件-appsettings.json。对于.NET Framework应用程序,可以将NLog配置放在app.configweb.config中。是否可以以相同方式将NLog配置放入appsettings.json

例如,如何将这个配置示例从NLog documentation for ASP.NET Core 2放入appsettings.json

<?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="c:\temp\internal-nlog.txt">

  <!-- enable asp.net core layout renderers -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <!-- the targets to write to -->
  <targets>
    <!-- write logs to file  -->
    <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />

    <!-- another file log, only own logs. Uses some ASP.NET core renderers -->
    <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-own-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
  </targets>

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

    <!--Skip non-critical Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" maxlevel="Info" final="true" /> <!-- BlackHole without writeTo -->
    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>

最佳答案

是的,这是可能的,但是具有最低版本要求。您必须使用NLog.Extensions.Logging> = 1.5.0。请注意,对于ASP.NET Core应用程序,如果安装NLog.Web.AspNetCore> = 4.8.2,则将作为依赖项安装。

然后,您可以在NLog中创建一个appsettings.json部分,并使用以下代码加载它:

var config = new ConfigurationBuilder()
  .SetBasePath(System.IO.Directory.GetCurrentDirectory())
  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).Build();
NLog.Config.LoggingConfiguration nlogConfig = new NLogLoggingConfiguration(config.GetSection("NLog"));


例如,对于ASP.NET Core应用程序,您在Main()中的Program.cs方法应如下所示:

public static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(System.IO.Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).Build();
    LogManager.Configuration = new NLogLoggingConfiguration(config.GetSection("NLog"));

    var logger = NLog.Web.NLogBuilder.ConfigureNLog(LogManager.Configuration).GetCurrentClassLogger();
    try
    {
        logger.Debug("Init main");
        CreateWebHostBuilder(args).Build().Run();
    }
    catch (Exception ex)
    {
        logger.Error(ex, "Stopped program because of exception");
    }
    finally {
        LogManager.Shutdown();
    }
}


可以使用appsettings.json中的以下设置来实现类似问题中的配置:

"NLog":{
    "internalLogLevel":"Info",
    "internalLogFile":"c:\\temp\\internal-nlog.txt",
    "extensions":{
        "NLog.Web.AspNetCore":{
            "assembly":"NLog.Web.AspNetCore"
        }
    },
    "targets":{
        "allfile":{
            "type":"File",
            "fileName":"c:\\temp\\nlog-all-${shortdate}.log",
            "layout":"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"
        },
        "ownFile-web":{
            "type":"File",
            "fileName":"c:\\temp\\nlog-own-${shortdate}.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"
        }
    ]
}


编辑:感谢Rolf Kristensen(他首先为NLog开发了此功能!)指出了此Wiki页面,并提供了有关此功能的更多文档:https://github.com/NLog/NLog.Extensions.Logging/wiki/Json-NLog-Config

关于asp.net-core - 如何使用appsettings.json而不是nlog.config文件在.NET Core中配置NLog?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56246416/

10-16 05:49