【问题标题】:Writing stack trace to log file only when exception thrown仅在抛出异常时将堆栈跟踪写入日志文件
【发布时间】:2011-09-27 00:28:30
【问题描述】:

我只想在有异常的时候才写堆栈跟踪,目前我是这样写的

 layout="${longdate}|${level}|${message} ${exception:format=tostring} | ${stacktrace}"

所以我总是在我的日志文件中得到它。

编辑:

我的所有日​​志记录都使用这个布局,所以当我没有任何异常时,我也会得到堆栈跟踪。但只有当我有一些异常时我才需要它

当我有异常时,我有以下输出,这是我需要的

2011-07-01 22:59:02.3782|Debug|fffffffffffffffffffffffffffff System.Exception: Exception of type 'System.Exception' was thrown. | AppDomain.ExecuteAssembly => AppDomain._nExecuteAssembly => Program.Main

但无一例外:

2011-07-01 22:57:26.7117|Trace|fffffffffffffffffffffffffffff  | AppDomain.ExecuteAssembly => AppDomain._nExecuteAssembly => Program.Main

但我只想要

2011-07-01 22:57:26.7117|Trace|fffffffffffffffffffffffffffff

需要想法如何做到这一点...

【问题讨论】:

  • 您是否希望有堆栈跟踪?
  • 你能澄清一下这个问题吗?给我们一些背景信息?
  • @Adrian,添加了一个例子

标签: c# .net logging nlog


【解决方案1】:

是的,在 NLog 中您可以使用不同级别的 Warn、Error Info 等。您还可以使用 ErrorException、WarnException、InfoException 记录异常。浏览器

logger.Error("This is an error message");

如果要显示异常,请使用以下内容。

logger.ErrorException("This is an error with an Exception", e);

更新:

<target name="Errors" xsi:type="File" fileName="${logDirectory}/ErrorLog.txt" layout="${longdate} ${message} ${exception:format=tostring}"/>

移除 {stacktrace}

更新:

Exception e = new Exception();
e.StackTrace // <= The exception holds the stack trace

您将从异常中获取堆栈跟踪。

【讨论】:

  • @Jetho ,但是当我没有异常时我不想获取堆栈跟踪
  • 如果你使用Error,而不是ErrorException,你不会得到异常堆栈跟踪。
  • 我还是明白了:2011-07-01 23:29:29.4367|调试|fffffffffffffffffffffffffff | AppDomain.ExecuteAssembly => AppDomain._nExecuteAssembly => Program.Main
  • 但是当我抛出异常时我不会记录它们,但是当我有异常时我需要堆栈跟踪
  • 异常包含堆栈跟踪。查看上面的示例。
【解决方案2】:

您可以使用以下布局:

${longdate}|${level}|${message} ${onexception:${exception:format=tostring} | ${stacktrace}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    相关资源
    最近更新 更多