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

3

我在工作中编写了一些控制台应用程序。我想在它们中加入NLog,但是我遇到了困难。

当我检查“logger”对象时,在其“Factory”属性中,我看到配置有targets=0,loggingrules=0,所有内容都为空或未设置。

所以,它什么也不做,也不会丢弃内部日志文件……我已经尝试过nLog.config、NLog.config和nlog.config……都没有成功。我还尝试了NLog的3和4版本…

为什么它不能读取配置文件?

我已经:

  • 在根目录下放置了NLog.config,并将构建操作设置为“Content”,同时设置“始终复制”
  • 确认NLog.config确实被复制到了bin文件夹中 screenshot1

这是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...");

我没有解决方案,但你的配置文件看起来很棒。我替换了我的一个配置文件(名为“Nlog.config”)的内容,它完全按照你的期望工作,将大量信息转储到控制台并按指示写入信息日志.log文件。在那个项目中,我也使用完全相同的logger.Info方法,并且设置了相同的构建操作。 - Micah
3个回答

3

你的 app.config 文件中是否有 NLog 的配置部分? 看起来应该像这样:

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

不需要,因为我正在使用外部的NLog.config文件。当您使用外部文件时,根据https://github.com/nlog/NLog/wiki/Configuration-file#configuration-file-locations,您不需要触及app.config。 - Beau D'Amore
@Beau,请问nloger.config文件是在应用程序的根目录下还是在应用程序的bin目录中?(例如:project/bin/bin) - Samuel Grave
在我的解释中:“使用“始终复制”设置的应用程序根目录”(因此它也会复制到bin目录)。 - Beau D'Amore
我的主要web.config文件中仍然有一个空的NLog节点...(web.config文件中有很多内容)它没有找到/加载NLog.config文件,因为它已经在web.config中找到了一个NLog节点...这是我的错误。 - Beau D'Amore
值得强调的是,<configuration> 元素应该放在 app.config 文件中的第一个位置。 - OfirD

1
如果连内部记录器都无法工作,您可以通过设置 InternalLogger.LogWriter 来调试问题。
例如:
 // enable internal logging to a custom TextWriter
    InternalLogger.LogWriter = new StringWriter(); //e.g. TextWriter writer = File.CreateText("C:\\perl.txt")

1

我在我的端口也遇到了同样的问题。当你将fileName路径“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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接