如何在文件中记录exception?
我希望能够记录每个catch块。 像这样的东西。
catch (Exception exception) { Logger.Write(exception); }
然后配置中的设置将使用客户监听器获取Message和StackTrace属性等。
我想使用Enterprise Library Logging Application Block。 我敢肯定有人必须已经这样做了。
其他人已经发布了一些关于使日志应用程序块(LAB)工作的良好链接,所以我不会在这里重复。
在格式化您的exception方面,您有三个我能想到的选择:
- 使用默认的
Exception.ToString()
实现(它还不错) - 编写一个集成到LAB中的自定义格式化程序。
- 编写一个执行格式化的辅助函数,并将该字符串传递给Write方法。
如果选项1不符合您的需求,那么我建议使用选项3(因为选项2是过度杀伤)。
一个简单的例子是:
catch (Exception exception) { Logger.Write(LogHelper.CreateExceptionString(exception)); } ... public static string CreateExceptionString(Exception e) { StringBuilder sb = new StringBuilder(); CreateExceptionString(sb, e, String.Empty); return sb.ToString(); } private static void CreateExceptionString(StringBuilder sb, Exception e, string indent) { if (indent == null) { indent = String.Empty; } else if (indent.Length > 0) { sb.AppendFormat("{0}Inner ", indent); } sb.AppendFormat("Exception Found:\n{0}Type: {1}", indent, e.GetType().FullName); sb.AppendFormat("\n{0}Message: {1}", indent, e.Message); sb.AppendFormat("\n{0}Source: {1}", indent, e.Source); sb.AppendFormat("\n{0}Stacktrace: {1}", indent, e.StackTrace); if (e.InnerException != null) { sb.Append("\n"); CreateExceptionString(sb, e.InnerException, indent + " "); } }
Microsoft在此提供了大量指导: 使用日志记录应用程序块开发应用程序
非常值得熟悉他们所说的内容,因为它非常强大。
如果你想要更实际的东西,本博客文章中提供了一些工作示例: 如何配置和使用日志记录应用程序块
如果您在阅读后仍然遇到问题,请编辑您的post,其中包含有关问题的详细信息。
@iSid这就是你要求的
public static void printException(Exception ex){ Console.WriteLine("HelpLink = {0}", ex.HelpLink); Console.WriteLine("Message = {0}", ex.Message); Console.WriteLine("Source = {0}", ex.Source); Console.WriteLine("StackTrace = {0}", ex.StackTrace); Console.WriteLine("TargetSite = {0}", ex.TargetSite); }
您需要为Text文件添加适当的侦听器 – 请参阅此文章,它适用于ASP.NET,但配置文件在应用程序中的工作方式相同。