如何使用 appsettings.json 而不是 nlog.config 文件在 .NET Core 中配置 NLog? [英] How can I configure NLog in .NET Core with appsettings.json instead of an nlog.config file?

查看:42
本文介绍了如何使用 appsettings.json 而不是 nlog.config 文件在 .NET Core 中配置 NLog?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The NLog documentation explains how to configure NLog for .NET Core applications by using an nlog.config XML file. However, I'd prefer to have just one configuration file for my application - appsettings.json. For .NET Framework apps, it's possible to put the NLog configuration in app.config or web.config. Is it possible to put the NLog config in appsettings.json in the same way?

例如,我怎么能把这个配置示例来自 将 ASP.NET Core 2 的 NLog 文档 写入 appsettings.json?

For example, how could I put this configuration example from the NLog documentation for ASP.NET Core 2 into 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:	empinternal-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:	emp
log-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:	emp
log-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,这将作为依赖项安装.

Yes, this is possible but has a minimum version requirement. You must be using NLog.Extensions.Logging >= 1.5.0. Note that for ASP.NET Core applications this will be installed as a dependency if you install NLog.Web.AspNetCore >= 4.8.2.

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

You can then create an NLog section in appsettings.json and load it with the following code:

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 应用程序,Program.cs 中的 Main() 方法应如下所示:

For example, for an ASP.NET Core application, your Main() method in Program.cs should look something like this:

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中的以下设置来实现类似问题中的配置:

A configuration like the one in the question can be achieved with the following settings in appsettings.json:

"NLog":{
    "internalLogLevel":"Info",
    "internalLogFile":"c:\temp\internal-nlog.txt",
    "extensions": [
      { "assembly": "NLog.Extensions.Logging" },
      { "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/NLog-configuration-with-appsettings.json

Thanks to Rolf Kristensen (who developed this functionality for NLog in the first place!) for pointing out this wiki page with more documentation on this feature: https://github.com/NLog/NLog.Extensions.Logging/wiki/NLog-configuration-with-appsettings.json

这篇关于如何使用 appsettings.json 而不是 nlog.config 文件在 .NET Core 中配置 NLog?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆