gpt4 book ai didi

c# - LogManager.configuration 为空

转载 作者:太空狗 更新时间:2023-10-29 18:18:17 27 4
gpt4 key购买 nike

我已将使用 nuget 的 NLog 添加到项目中并添加了 NLog.config。由于 LogManager.Configuration 为 null,我正在运行调试器并收到 NullReferenceException:

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 文件复制到单元测试主目录。运行单元测试时问题仍然存在。

最佳答案

  • 将 NLog.config 复制到测试项目的顶级文件夹
  • DeploymentItemAttribute 添加到测试类 ( more info )

像这样:

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

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

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

关于c# - LogManager.configuration 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23389343/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com