如何在文件中记录异常?

时间:2010-06-07 12:25:20

标签: c# wcf logging enterprise-library

我希望能够记录每个catch块。这样的事情。

catch (Exception exception)
{
  Logger.Write(exception);
}

然后配置中的设置将使用客户监听器获取Message和StackTrace属性等。

我想使用Enterprise Library Logging Application Block。我相信某人肯定已经这样做了。

4 个答案:

答案 0 :(得分:31)

其他人已经发布了一些关于让Logging Application Block(LAB)工作的好链接,所以我不会在这里复制。

在格式化您的例外方面,您有三个我能想到的选择:

  1. 使用默认的Exception.ToString()实施(不错)
  2. 编写一个集成到LAB中的自定义格式化程序。
  3. 编写一个执行格式化的辅助函数,并将该字符串传递给Write方法。
  4. 如果选项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 + "  ");
            }
        }
    

答案 1 :(得分:4)

Microsoft已在此处提供了广泛的指导:Developing Applications Using the Logging Application Block

非常值得熟悉他们所说的内容,因为它非常强大。

如果您想要更加实际的内容,本博客文章中提供了一些有用的示例:How To Configure and Use the Logging Application Block

如果您在阅读完毕后仍然遇到问题,请使用更具体的详细信息编辑您的帖子。

答案 2 :(得分:1)

@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);

            }

答案 3 :(得分:0)

您需要为文本文件添加适当的侦听器 - 请参阅this post,它适用于ASP.NET,但配置文件在应用程序中的工作方式相同。

相关问题