Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

c# - How to Log Exception in a file?

I want to be able to do logging in every catch block. Something like this.

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

and then the settings in the configuration will pick up the Message and StackTrace property etc using customer listener.

I would like to use Enterprise Library Logging Application Block. I'm sure someone must have done this already.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Others have posted some good links on getting the Logging Application Block (LAB) working so I won't duplicate that here.

In terms of formatting your exception you have 3 choices that I can think of:

  1. Use the default Exception.ToString() implementation (it's not bad)
  2. Write a Custom Formatter that integrates into the LAB.
  3. Write a helper function that performs the formatting and passes the string into the Write method.

If option 1 doesn't meet your needs then I would recommend going with option 3 (since option 2 is overkill).

A simple example would be something like:

    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:
{0}Type: {1}", indent, e.GetType().FullName);
        sb.AppendFormat("
{0}Message: {1}", indent, e.Message);
        sb.AppendFormat("
{0}Source: {1}", indent, e.Source);
        sb.AppendFormat("
{0}Stacktrace: {1}", indent, e.StackTrace);

        if (e.InnerException != null)
        {
            sb.Append("
");
            CreateExceptionString(sb, e.InnerException, indent + "  ");
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...