我已经使用nuget将NLog添加到项目中并添加了NLog.config。由于NullReferenceException
为空,我正在运行调试器并获得LogManager.Configuration
:
LogManager.Configuration.AddTarget("sentinel", sentinalTarget);
这行代码在静态构造函数中运行。
LogManager.ThrowExceptions
为false,所以我怀疑配置问题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"
throwExceptions="false">
<variable name="appName" value="YourAppName" />
<targets async="true">
<target xsi:type="File"
name="default"
layout="${longdate} - ${level:uppercase=true}: ${message}${onexception:${newline}EXCEPTION\: ${exception:format=ToString}}"
fileName="${specialfolder:ApplicationData}\${appName}\Debug.log"
keepFileOpen="false"
archiveFileName="${specialfolder:ApplicationData}\${appName}\Debug_${shortdate}.{##}.log"
archiveNumbering="Sequence"
archiveEvery="Day"
maxArchiveFiles="30"
/>
<target xsi:type="EventLog"
name="eventlog"
source="${appName}"
layout="${message}${newline}${exception:format=ToString}"/>
<target xsi:type="NLogViewer"
name="viewer"
address="udp://127.0.0.1:9999"/>
<target xsi:type="OutputDebugString" name="DbWin" layout="Log4JXmlEventLayout">
<layout xsi:type="Log4JXmlEventLayout" />
</target>
</targets>
<rules>
<logger name="*" writeTo="default" minlevel="Info" />
<logger name="*" writeTo="eventlog" minlevel="Error" />
<logger name="*" minlevel="Debug" writeTo="viewer" />
<logger name="*" minlevel="Trace" writeTo="DbWin" />
</rules>
</nlog>
更新
我发现了消息来源。仅在运行单元测试时才会出现此问题。运行完整的应用程序(Web应用程序)问题不存在。我将NLog.config文件复制到单元测试主目录。运行单元测试时问题仍然存在。
答案 0 :(得分:13)
DeploymentItemAttribute
添加到测试类(more info)像这样:
[TestClass]
[DeploymentItem("ProjectName\\NLog.config")]
public class GeneralTests
或者,您可以以编程方式加载配置:
LogManager.Configuration = new XmlLoggingConfiguration(@"c:\path\to\NLog.config")