【问题标题】:Bad configuration of NLog?NLog 配置错误?
【发布时间】:2010-12-29 17:38:53
【问题描述】:

好的,所以我正在尝试 NLog,但它一直在跌倒。让我来看看我到目前为止所得到的。

我的 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="file" xsi:type="File"
            layout="${longdate} ${logger} ${message}"
            fileName="${basedir}/Logs/${shortdate}.log" />
    </targets>

    <rules>
        <logger name="*" minlevel="Debug" writeTo="file" />
    </rules>
</nlog>

然后我像这样创建我的对象:

private static Logger logger = LogManager.GetCurrentClassLogger();

然后当我想记录一些事情时,我会这样做:

try
{   
    // Do something
}
catch (Exception ex)
{
    logger.Fatal("ERROR {0}", ex);
    return null;
}

但我收到以下错误:

System.TypeInitializationException was unhandled
Message="The type initializer for 'Rhs.CMSSites.Services.GetBlogFeeds' threw an exception."
Source="GetBlogFeeds"
TypeName="Rhs.CMSSites.Services.GetBlogFeeds"
StackTrace:
   at Rhs.CMSSites.Services.GetBlogFeeds.Main(String[] args)
   at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.NullReferenceException
   Message="Object reference not set to an instance of an object."
   Source="GetBlogFeeds"
   StackTrace:
        at Rhs.CMSSites.Services.GetBlogFeeds.UserDetails(String UserName) in C:\Dev\Rhs.CMSSites.Services\GetBlogFeeds\GetBlogFeeds\Program.cs:line 217
        at Rhs.CMSSites.Services.GetBlogFeeds..cctor() in C:\Dev\Rhs.CMSSites.Services\GetBlogFeeds\GetBlogFeeds\Program.cs:line 25
   InnerException: 

有什么想法吗?

编辑

可能应该在前面提到过,但这是一个命令行应用程序。 GetBlogFeeds 是类的名称。

编辑2

好吧,我真是个白痴。我在实例化记录器类之前调用​​了UserDetails() 方法(它尝试使用NLog 方法)。我要给你们两个投票。谢谢和抱歉。

【问题讨论】:

    标签: c# nlog


    【解决方案1】:

    我的猜测(仅此而已)是这与 NLog 无关,而是TypeInitializationException 是如此严重和/或没有发生在 NLog 没有的try ... catch 的上下文中没有机会记录它。

    如果您在logger.Fatal 语句上设置断点,当您在附加调试器的情况下运行时,执行是否会停止?

    GetBlogFeeds 的类 ctor 中实际发生的事情 - 从堆栈跟踪来看,您似乎为 特定 用户调用 UserDetails,这似乎有点奇怪 ctor.

    【讨论】:

      【解决方案2】:

      为什么发生异常时返回null?

      基于发布的异常是因为空异常,当然也可能是您尝试记录整个异常对象而不是它的消息。

      请确定您是否同意此答案并将其标记为答案。如果您对发布的错误有其他问题,我可以回答。如果没有更多信息(例如),您的代码中究竟发生了哪些错误,我无法提供更多信息。

      我只是指出了两个奇怪的行为。

      【讨论】:

      • 在我尝试使其正常工作时暂时返回 null。
      • 除了,返回是整个问题,尝试将方法更改为 void 以查看它是否仍然崩溃。就像 AskashM 说的你还有其他问题。除了你返回 null 是不好的做法,如果你不稍后检查它,并避免基于该 null 异常实际使用 null 值(你是)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多