我有一个用.NET 4.0编写的Windows服务,并在Local System凭据下安装了它。在代码中,我使用了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");
然后它就可以工作了。我不确定我的第一组配置有什么问题。
<target name="logfile" xsi:type="File" fileName="C:/log/TestService/My.log" layout="${longdate}::${logger}::${message}" keepFileOpen="false" />
否则:你有一个独立的NLog.config文件,对吧?如果是这样,它可能没有被构建(在你的/bin目录中)--> 所以服务将找不到它所需的配置!在这里看看。 - Matthias R.<logger name="*" minlevel="Info" maxLevel="Deubg" writeTo="logfile" />
应该实际上是maxLevel="Debug"
? - Matthias R.