c# - 如何记录异常信息以进行故障排除?

标签 c# .net exception logging

我目前正在对 Windows 服务进行维护,并且在代码中的某些点有一些异常处理(例如在来自计时器和其他外部事件的回调中):

try {
  ...
}
catch (Exception ex) {
   _logger.Log("Unhandled exception: {0}\r\n{1}", ex.Message, ex.StackTrace);
   Environment.FailFast("Fatal error.");
}

记录异常信息有助于解决问题。然而,有时有趣的信息是内部异常,这使得很难确定问题的根本原因。例如,TypeInitializationException 可能很难理解。

有没有更好的方法来记录异常信息以进行故障排除?

最佳答案

Is there a better way to log exception information for troubleshooting purposes?

是的。不要太“聪明”,不要使用 ex.Messageex.StackTrace。只需使用 ex.ToString()。它将递归到内部异常(如果需要,则为多个级别)并显示完整的堆栈跟踪。

try {
  ...
}
catch (Exception ex) {
   _logger.Log("Unhandled exception:\r\n{0}", ex);
   Environment.FailFast("Fatal error.");
}

举个小例子,如果你创建了一个在类的静态构造函数中抛出异常的类的实例,你会得到这样的结果。此异常抛出将包装在 TypeInitializationException 中。

之前:

Unhandled exception: The type initializer for 'SomeClass' threw an exception.
   at SomeNamespace.SomeClass..ctor()
   at SomeNamespace.Callback() in c:\ExceptionHandlingDemo.cs:line 34

帮助不大。很难确定哪里出了问题。

之后:

Unhandled exception:
System.TypeInitializationException: The type initializer for 'SomeClass' threw an exception. ---> System.ArgumentException: An item with the same key has already been added.
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
   at SomeNamespace.SomeClass..cctor() in c:\ExceptionHandlingDemo.cs:line 43
   --- End of inner exception stack trace ---
   at SomeNamespace.SomeClass..ctor()
   at SomeNamespace.Callback() in c:\ExceptionHandlingDemo.cs:line 34

现在您可以很容易地确定问题的根本原因是字典中的重复键,并将其精确定位到源文件中的第 43 行。

关于c# - 如何记录异常信息以进行故障排除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11898293/

相关文章:

c# - 如何将表值参数从 C# 传递到 Oracle 存储过程

c# - MVC 4 中数据库方法的最佳实践

c# - 新的 is 模式匹配语法可以与现有变量一起使用吗?

java - PDFBox PDFMergerUtility : how do I tell which sources failed?

c# - 从隔离存储中将视频从手机传输出去

.net - 我可以创建项目特定的代码片段吗?

c# - 运行时代码覆盖工具

c# - 如何找到数组的模式(最频繁的元素)?

mysql - SQl 数据库备份显示错误 "Exception of type "System.OutofMemoryException“被抛出。(mscorlib)”

ios - objective-c 没有在 try/catch block 中捕获异常