LogManager.configuration 为空

问题描述 投票:0回答:2

我已使用 nuget 将 NLog 添加到项目中,并添加了 NLog.config。我正在运行调试器并得到

NullReferenceException
,因为
LogManager.Configuration
为空:

LogManager.Configuration.AddTarget("sentinel", sentinalTarget);

这行代码在静态构造函数中运行。

  • NLog.config 位于项目根目录中,与 web.config 一起。
  • 这发生在 Visual Studio 调试器中
  • NLog.config 属性“复制到输出目录”=“始终复制”
  • 我更新了 NLog.config throwExceptions="true" 并且在运行时
    LogManager.ThrowExceptions
    是 false,所以我怀疑配置有问题
  • 尝试删除名称为:viewer、DbWin 的目标及其相关规则

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>

更新
我发现了源头。仅当运行单元测试时才会出现此问题。运行完整的应用程序(网络应用程序),问题不存在。我将 NLog.config 文件复制到单元测试主目录。运行单元测试时问题仍然存在。

c# nlog
2个回答
20
投票
  • 将 NLog.config 复制到测试项目顶级文件夹
  • DeploymentItemAttribute
    添加到测试类(更多信息

像这样:

[TestClass]
[DeploymentItem("ProjectName\\NLog.config")]
public class GeneralTests

或者,您可以通过编程方式加载配置:

LogManager.Configuration = new XmlLoggingConfiguration(@"c:\path\to\NLog.config")


2
投票

确保您的 nlog.config 位于 NLog 扫描以查找配置文件的文件夹之一。例如可执行文件的文件夹。

如果您使用 Visual Studio,您可以像这样配置它以自动执行复制过程:

© www.soinside.com 2019 - 2024. All rights reserved.