仅在抛出异常时将堆栈跟踪写入日志文件

Nig*_*ker 7 .net c# logging nlog

我只想在有异常时编写堆栈跟踪,目前我这样做

 layout="${longdate}|${level}|${message} ${exception:format=tostring} | ${stacktrace}"
Run Code Online (Sandbox Code Playgroud)

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

编辑:

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

当我有一个例外我有以下输出,它是我需要的

2011-07-01 22:59:02.3782|Debug|fffffffffffffffffffffffffffff System.Exception: Exception of type 'System.Exception' was thrown. | AppDomain.ExecuteAssembly => AppDomain._nExecuteAssembly => Program.Main
Run Code Online (Sandbox Code Playgroud)

但无一例外:

2011-07-01 22:57:26.7117|Trace|fffffffffffffffffffffffffffff  | AppDomain.ExecuteAssembly => AppDomain._nExecuteAssembly => Program.Main
Run Code Online (Sandbox Code Playgroud)

但我只想要

2011-07-01 22:57:26.7117|Trace|fffffffffffffffffffffffffffff
Run Code Online (Sandbox Code Playgroud)

需要创意如何做到这一点......

ogu*_*gun 13

您可以使用以下布局:

${longdate}|${level}|${message} ${onexception:${exception:format=tostring} | ${stacktrace}}
Run Code Online (Sandbox Code Playgroud)


Jet*_*hro 2

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

logger.Error("This is an error message");
Run Code Online (Sandbox Code Playgroud)

如果您想显示异常,请使用以下命令。

logger.ErrorException("This is an error with an Exception", e);
Run Code Online (Sandbox Code Playgroud)

更新 :

<target name="Errors" xsi:type="File" fileName="${logDirectory}/ErrorLog.txt" layout="${longdate} ${message} ${exception:format=tostring}"/>
Run Code Online (Sandbox Code Playgroud)

删除{堆栈跟踪}

更新 :

Exception e = new Exception();
e.StackTrace // <= The exception holds the stack trace
Run Code Online (Sandbox Code Playgroud)

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