2

你好亲爱的开发者,

我在使用 NLog 时遇到了一个奇怪的问题,
我遇到了崩溃,但在日志中找不到用户活动的踪迹。

我假设,日志记录不起作用......
尝试搜索权限问题等,但一切似乎都很好

我想在出现问题时调试我的日志记录,所以我创建了以下
代码来告诉用户它是否未能创建任何内容:

public static class Log
{
    static Log()
    {
        try
        {
            AppLogger = LogManager.GetLogger("Megatec.EngineeringMatrix.AppLogger");
            ChangeLogger = LogManager.GetLogger("Megatec.EngineeringMatrix.ChangeLogger");
            DRCLogger = LogManager.GetLogger("Megatec.EngineeringMatrix.DRCLogger");

            if((AppLogger == null) || (ChangeLogger == null) || (DRCLogger == null))
                throw new NLogConfigurationException("Configuration does not specify correct loggers");
            writeStartupLogEntry();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString(), @"Failed to load `Megatec.EngineeringMatrix` Loggers.");
            throw;
        }

    }

    public static readonly Logger AppLogger;
    public static readonly Logger ChangeLogger;
    public static readonly Logger DRCLogger;

使用以下配置文件:

  <?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" throwExceptions="true">
    <targets>
      <target xsi:type="File" name="AppLogFile" createDirs="true" fileName="c:/log?s/${processname}/${logger}_${shortdate}.log"
              layout=">> ${time} ${uppercase:${level}} ${callsite} ${message} ${exception:format=tostring}" />

      <target xsi:type="File" name="ChangeLogFile" createDirs="true" fileName="c:/log?s/${processname}/${logger}_${shortdate}.log"
              layout=">> ${date} ${message} ${exception:format=tostring}" />

      <target xsi:type="File" name="DRCLogFile" createDirs="true" fileName="c:/logs/${processname}/${logger}_${shortdate}.log"
              layout=">> ${date} ${message} ${exception:format=tostring}" />
    </targets>

    <rules>
      <logger name="Megatec.EngineeringMatrix.AppLogger" minlevel="Trace" writeTo="AppLogFile" />
      <logger name="Megatec.EngineeringMatrix.ChangeLogger" minlevel="Trace" writeTo="ChangeLogFile" />
      <logger name="Megatec.EngineeringMatrix.DRCLogger" minlevel="Trace" writeTo="DRCLogFile" />
    </rules>
  </nlog>

显然我写了一个 BAAD 配置,因为c:\lo?gs无法创建目录。

但是,我仍然没有收到消息
MessageBox.Show(ex.ToString(), @"Failed to load 'Megatec.EngineeringMatrix'

甚至AppLogger.Info()跳过异常...

我没有写任何东西来记录,但应用程序不知道......

在调试中,我可以捕捉到异常,并看到它是由 NLog 处理的,

如何从我的代码中捕获它?

4

1 回答 1

1

这是一个老问题,但最近有一些变化。

NLog 过去曾“吃掉”一些异常。例如在AsyncWrapper(或使用属性asyncon <target>

这已在 NLog 4.3 中修复:

异常的一致处理(行为变化) 异常的记录和抛出以前是不一致的。并非所有这些都记录到内部记录器中,有时它们会丢失。例如,异步包装器(或异步属性)在没有适当重新抛出的情况下捕获所有异常。

这很糟糕,因为有时不清楚为什么 NLog 不起作用(我自己多次得到它)。这已在 NLog 4.3 中修复!

所有异常都记录到内部记录器中。“throwExceptions”选项在所有情况下都将受到尊重建议:在生产环境中禁用 throwExceptions!(这是默认值)

http://nlog-project.org/2016/04/16/nlog-4-3-has-been-released.html

于 2016-09-26T21:16:09.017 回答