C# 仅当引发异常时才将堆栈跟踪写入日志文件

C# 仅当引发异常时才将堆栈跟踪写入日志文件,c#,.net,logging,nlog,C#,.net,Logging,Nlog,我只想在出现异常时才编写堆栈跟踪,目前我是这样做的 layout="${longdate}|${level}|${message} ${exception:format=tostring} | ${stacktrace}" 所以我总是把它放在我的日志文件里 编辑: 我所有的日志记录都使用这个布局,所以当我没有任何异常时,我也会得到堆栈跟踪。但只有当我有一些异常时,我才需要它 当我有一个异常时,我有以下输出,它是我所需要的 2011-07-01 22:59:02.3782|Debug|ffff

我只想在出现异常时才编写堆栈跟踪,目前我是这样做的

 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

需要如何做到这一点的想法…

是的,在NLog中,您可以使用不同级别的警告、错误信息等。您还可以使用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
Exception e=newexception();

e、 StackTrace/您可以使用以下布局:

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

你希望堆栈跟踪不是这样吗?你能澄清这个问题吗?“给我们一些背景?”阿德里安补充道example@Jetho,但我不想在没有例外的情况下获取堆栈跟踪如果使用错误,除了ErrorException之外,您不会得到异常堆栈跟踪。我仍然可以看到:2011-07-01 23:29:29.4367 | Debug | fffffffffffffffff | AppDomain.ExecuteAssembly=>AppDomain.\u nexecuteSembly=>Program.main但是当我抛出异常时,我不会记录它们,但是当我有一个异常时,我需要堆栈跟踪这个异常保存堆栈跟踪。查看上面的示例。