【问题标题】:Nlog Error(message, exception) ignore exceptionNlog 错误(消息,异常)忽略异常
【发布时间】:2014-06-10 01:39:03
【问题描述】:

我有问题日志异常只记录消息。

NLog 配置:

<target name="logfile"
        xsi:type="File"
        fileName="log.txt"
        layout="${longdate} | ${machinename} | ${processid} | ${processname} | ${level} | ${logger} | |${message} | ${exception:format=tostring}" />



<logger name="*"
        minlevel="Info"
        writeTo="logfile" />

用法:

    private static Logger _logger = LogManager.GetCurrentClassLogger();

    _logger.Error("my message", new Exception("my exception"));

日志输出:

2014-04-24 18:17:29.0841 | PC_NAME | 6464 | APP_NAME.vshost | Error | AppName.ViewModel | my message |

异常被忽略。

我找到了一些thread,但对我来说不起作用。

【问题讨论】:

    标签: exception error-handling .net-3.5 nlog


    【解决方案1】:

    其实void Error(string message, Exception exception);已经过时了

    您可以使用ILogger.Error(Exception, string) 方法,如下所示

    catch (Exception e)
    {
     Log.Error(e, "it happens");
    }
    

    并使用${onexception} 稍微修改了布局。这将检查是否有要记录的异常

    <target name="logfile"
            xsi:type="File"
            fileName="log.txt"
            layout="${longdate} | ${machinename} | ${processid} | ${processname} | ${level} | ${logger} | |${message} ${onexception:| ${exception:format=tostring}}" />
    

    />

    【讨论】:

      【解决方案2】:

      Nlog 使用特殊的方法来记录使用&lt;loglevel&gt;Exception 命名模式的异常。

      因此,在您的情况下,您需要使用 ErrorException 方法才能正确记录您的异常:

      private static Logger _logger = LogManager.GetCurrentClassLogger();
      
      _logger.ErrorException("my message", new Exception("my exception"));
      

      【讨论】:

      • NLog 的 ErrorException 方法已被弃用。
      猜你喜欢
      • 1970-01-01
      • 2011-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      • 1970-01-01
      • 2022-06-16
      相关资源
      最近更新 更多