.NET 4.5 控制台应用程序中的 NLog:未加载配置

NLog in .NET 4.5 console app: not loading Configuration

我有一些在工作中编写的控制台应用程序。我想让 NLog 加入其中,但我遇到了麻烦。 当我检查 'logger' 对象时,我在它的 'Factory' 属性 中看到配置有 targets=0,loggingrules=0,一切都是空白或未设置。 所以,它没有做任何事情.. 也不会删除内部日志文件......我试过 nLog.config NLog.config 和 nlog.config... 无济于事。也尝试了 NLog 的第 3 版和第 4 版...

为什么它不获取配置?

我有:

这是NLog.config:

<?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"
      throwConfigExceptions="true"
      throwExceptions="true"
      internalLogLevel="Trace"
      internalLogFile="c:\temp\NlogInternal.log"
      internalLogToConsole="true"
      internalLogToConsoleError="true"
      internalLogToTrace="true">
  <targets>
    <target xsi:type="Console" name="debugConsole" layout="${message} "/>
    <target xsi:type="File" name="debugFile" createDirs="true" fileName="c:\temp\testlog.log" layout="${longdate} ${uppercase:${level}} ${message}"/>
  </targets>
  <rules>
    <logger name="*" minlevel="Trace" writeTo="debugConsole"/>
    <logger name="*" minlevel="Trace" writeTo="debugFile"/>    
  </rules>
</nlog>

最后(这不会出错,但由于配置为空,因此不会输出任何内容):

private static Logger logger = LogManager.GetCurrentClassLogger();
logger.Info("ConsoleApp test log...");

你的 app.config 有 NLog configSection 吗? 像这样:

<configuration>
  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
  </configSections>
  <nlog>
  </nlog>
</configuration>

如果连 internalLogger 都不工作,您可以通过设置来调试问题 InternalLogger.LogWriter

例如

 // enable internal logging to a custom TextWriter
    InternalLogger.LogWriter = new StringWriter(); //e.g. TextWriter writer = File.CreateText("C:\perl.txt")

我这边遇到了同样的问题。当您将文件名路径 "c:\temp\testlog.log" 更改为 "c:/temp/testlog.log" 就可以了。希望下面的代码片段能帮助您解决问题。

<targets>
  <target xsi:type="Console" name="debugConsole" layout="${message} "/>
  <target xsi:type="File" name="debugFile" createDirs="true" 
      fileName="c:/temp/testlog.log" layout="${longdate} ${uppercase:${level}} 
      ${message}"/>
 </targets>
 <rules>
    <logger name="*" minlevel="Trace" writeTo="debugConsole"/>
    <logger name="*" minlevel="Trace" writeTo="debugFile"/>
 </rules>