我正在解决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>