我已经使用nuget将NLog添加到项目中并添加了NLog.config.我正在运行调试器并得到一个NullReferenceException由于事实LogManager.Configuration是null:
LogManager.Configuration.AddTarget("sentinel", sentinalTarget);
这行代码在静态构造函数中运行.
LogManager.ThrowExceptions是假的,所以我怀疑配置有问题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>
Run Code Online (Sandbox Code Playgroud)
更新
我发现了源.仅在运行单元测试时才会出现此问题.运行完整的应用程序(Web应用程序)问题不存在.我将NLog.config文件复制到单元测试主目录.运行单元测试时仍然存在问题.
P.B*_*key 14
DeploymentItemAttribute到测试类(更多信息)像这样:
[TestClass]
[DeploymentItem("ProjectName\\NLog.config")]
public class GeneralTests
Run Code Online (Sandbox Code Playgroud)
或者,您可以以编程方式加载配置:
LogManager.Configuration = new XmlLoggingConfiguration(@"c:\path\to\NLog.config")