【问题标题】:Nlog does not write to log file in windows serviceNlog 不会写入 Windows 服务中的日志文件
【发布时间】:2014-08-07 13:42:44
【问题描述】:

我有一个用 .net 4.0 编写的 Windows 服务,我在本地系统的凭据下安装了它。在我使用nlog的代码中,

private static Logger logger = LogManager.GetCurrentClassLogger();
logger.Debug("some information");

我也将 nlog.config 复制到 exe 文件所在的同一目录

<?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">
  <targets>
    <target name="logfile" type="File"
            fileName="c:\log\TestService\My.log"
            layout="${longdate}::${logger}::${message}"
            keepFileOpen="false" />
  </targets>

  <rules>
    <logger name="*" minlevel="Info" maxLevel="Deubg" writeTo="logfile" />
  </rules>
</nlog>

但是如果我启动服务,我根本看不到日志文件已经创建。如果我将log.Debug 代码交换为Debug.WriteLine 并使用我的Visual Studio 附加到Windows 服务进程进行调试,我可以看到输出窗口有我的调试消息,这意味着我的Windows 服务代码是正确的。

我的 nlog 代码有问题吗?

-- 更新1--

我将 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">
  <targets>
    <target name="logfile" type="File"
            fileName="c:\log\TestService\My.log"
            layout="${longdate}::${logger}::${message}"
            keepFileOpen="false" />
  </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="logfile" />
  </rules>
</nlog>

并将我的代码更改为

logger.Trace("some information");

然后就可以了。我不确定我的第一组配置有什么问题。

【问题讨论】:

  • 我猜 LocalSystem 没有对该文件夹的写入权限。
  • 乍一看,我会说你的目标标签应该是这样的:&lt;target name="logfile" xsi:type="File" fileName="C:/log/TestService/My.log" layout="${longdate}::${logger}::${message}" keepFileOpen="false" /&gt; 否则:你有一个独立的 NLog.config 文件,对吧?如果是这样,它可能不会被构建(在你的 /bin 目录中)--> 所以服务将找不到它需要的配置!看看here
  • @Matt 看到我上面更新的问题,我不太明白调试和跟踪之间有什么区别。
  • 只是为了确定:您是否在第一次尝试时认出了拼写错误? &lt;logger name="*" minlevel="Info" maxLevel="Deubg" writeTo="logfile" /&gt; 实际上应该在哪里说 maxLevel="Debug"
  • @Matt,不错的收获!!这可能是问题所在。

标签: c# windows-services nlog


【解决方案1】:

更新

<logger name="*" minlevel="Info" maxLevel="Deubg" writeTo="logfile" />
                                           ^^^^^

首先:Debug 拼写错误。

但主要问题是 Debug 级别在 info 级别之下

以下是允许的日志级别(按降序排列):

  • 关闭
  • 致命
  • 错误
  • 警告
  • 信息
  • 调试
  • trace(最详细的信息。)

Link to the nlog documentation

【讨论】:

  • 要更深入地了解何时使用哪个日志级别,请参阅 nlog documentation
  • "首先:debug 拼写错误。" - 如果在指出调试中的字符被转置时首先转置字符是故意的、聪明的和聪明的。
猜你喜欢
  • 2011-11-23
  • 2010-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-27
相关资源
最近更新 更多