NLog 无法读取 .NET Core 2.2 控制台应用程序中的 app.config configSection

NLog can't read app.config configSection in .NET Core 2.2 console app

我正在解决 NLog 未从 .NET Core 2.2 控制台应用程序中的 App.config 加载其配置的问题。

当调用 NLog.LogManager.GetCurrentClassLogger() 时,生成的对象是空白的,没有日志记录目标或其他配置。

<appSettings> 配置项可以使用通常的方法毫无问题地查找:ConfigurationManager.AppSettings["settingKey"].

在尝试解决这个问题的过程中,我打电话给 ConfigurationManager.GetSection("nlog") 看看我是否可以手动获取设置。这引发了以下异常:

System.Configuration.ConfigurationErrorsException: 
'An error occurred creating the configuration section handler for nlog: 
Could not load type 'NLog.Config.ConfigSectionHandler' from assembly 'NLog'

我的示例应用程序中的整个 app.config 如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
  </configSections>
  <appSettings>
    <add key="value1" value="TEST1"/>
    <add key="value2" value="TEST2"/>
  </appSettings>
  <nlog>
    <targets>
      <target name="logfile" type="File" fileName="${basedir}/logs/${shortdate}.log" layout="${longdate} ${uppercase:${level}} ${message}" />
      <target name="logconsole" type="Console" />
    </targets>
    <rules>      
      <logger name="*" minlevel="Info" writeTo="logconsole"/>
      <logger name="*" minlevel="Info" writeTo="logfile"/>
    </rules>
  </nlog>
</configuration>

NLog 是 nuget 的 4.6.7 版。

如果其他人 运行 参与其中:

由于 NLog 在 .NET Core 中不支持 app.config,我的解决方案是创建一个单独的 nlog.config(使用 SlowCheetah 环境转换)和 运行 NLog.LogManager.LoadConfiguration(".\nlog.config");在应用程序的开头。

除非有人想出一个巧妙的解决方法来将所有内容都保存在一个配置中,否则我会将其设置为答案。

可能有多种原因。我面临的一个原因是允许在指定文件夹中创建文件。由于以下代码,如果有任何内部错误将被记录到 bin 文件夹中的 Test_log.txt。还要确保目标文件夹可以访问以创建文件。

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true" internalLogLevel="Warn"
      internalLogFile="Test_log.txt">

  <extensions>
    <add assembly="Microsoft.ApplicationInsights.NLogTarget" />
  </extensions>

  <!-- the targets to write to -->
  <targets>
    <!-- write logs to file -->

    <target xsi:type="File" name="ownFile" fileName="C:\Logs\log_${shortdate}.log"
                 layout="${longdate}|${logger}|${uppercase:${level}}|  ${message} ${exception}" />

                 <target xsi:type="Null" name="blackhole" />

  </targets>

  <rules>
    <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
    <logger name="*" minlevel="Info" writeTo="ownFile" />
  </rules>
</nlog>