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

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

问题描述

NLog文档说明了如何使用 nlog.config XML文件为.NET Core应用程序配置NLog.但是,我希望我的应用程序只有一个配置文件- appsettings.json .对于.NET Framework应用程序,可以将NLog配置放在 app.config web.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 ?

<?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 .它将作为依赖项安装.

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":{
        "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页面,并提供了有关此功能的更多文档:

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/Json-NLog-Config

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

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