Asp.net-Core

如何使用 appsettings.json 而不是 nlog.config 文件在 .NET Core 中配置 NLog?

  • May 21, 2019

NLog 文件解釋瞭如何使用nlog.configXML 文件為 .NET Core 應用程序配置 NLog。但是,我希望我的應用程序只有一個配置文件 - appsettings.json. 對於 .NET Framework 應用程序,可以將 NLog 配置放入app.configweb.config. 是否可以以相同的方式放入 NLog 配置appsettings.json

例如,如何將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,它將作為依賴項安裝。

然後,您可以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": [
     { "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

引用自:https://stackoverflow.com/questions/56246416