How do I log exception information to allow troubl

2019-05-10 08:41发布

I'm currently doing maintenance on a Windows service and at certain points in the code there is some exception handling (e.g. in callbacks from timers and other external events):

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

Logging the exception information helps troubleshooting what went wrong. However, sometimes the interesting information is the inner exception which makes it hard to determine the root cause of the problem. For instance a TypeInitializationException can be hard to understand.

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

3条回答
Melony?
2楼-- · 2019-05-10 08:48

I don't know if this will help or if it is a too high a level, but are you aware of Microsoft's Enterprise Library? (http://msdn.microsoft.com/en-us/library/ff648951.aspx).

In it there is a logging "application block" which is something of a sledgehammer but ultimately very powerful/flexible. Having gone through the exercise of setting it up how I wanted (its all config-driven) this is now standard for exerything I build.

In particular with exceptions I don't think I had to do much at all in order to get meaningful information out.

查看更多
Ridiculous、
3楼-- · 2019-05-10 09:01

I am not sure if this will help. I wrote this Utility class to log all the information of exception, I use Exception.Data and Exception.Message to log info

something shared here : https://stackoverflow.com/a/15005319/1060656

public class ExceptionInfoUtil
{
    public static string GetAllExceptionInfo(Exception ex)
    {
        StringBuilder sbexception = new StringBuilder();

        int i = 1;
        sbexception.Append(GetExceptionInfo(ex, i));

        while (ex.InnerException != null)
        {
            i++;
            ex = ex.InnerException;
            sbexception.Append(GetExceptionInfo(ex, i));
        }

        return sbexception.ToString();
    }

    private static string GetExceptionInfo(Exception ex, int count)
    {
        StringBuilder sbexception = new StringBuilder();
        sbexception.AppendLine(string.Format(""));
        sbexception.AppendLine(string.Format(""));
        sbexception.AppendLine(string.Format("************************************************"));
        sbexception.AppendLine(string.Format("************************************************"));
        sbexception.AppendLine(string.Format(" Inner Exception : No.{0} ", count));
        sbexception.AppendLine(string.Format("************************************************"));
        sbexception.AppendLine(string.Format("=================================================="));
        sbexception.AppendLine(string.Format(" Error Message : {0} ", ex.Message));
        sbexception.AppendLine(string.Format("=================================================="));
        #region Mine Thru data dictionary

        try
        {
            sbexception.AppendLine(string.Format("=================================================="));
            sbexception.AppendLine(string.Format(" Data parameters Count at Source :{0}", ex.Data.Count));
            sbexception.AppendLine(string.Format("=================================================="));

            string skey = string.Empty;
            foreach (object key in ex.Data.Keys)
            {
                try
                {
                    if (key != null)
                    {
                        skey = Convert.ToString(key);
                        sbexception.AppendLine(string.Format(" Key :{0} , Value:{1}", skey, Convert.ToString(ex.Data[key])));
                    }
                    else
                    {
                        sbexception.AppendLine(string.Format(" Key is null"));
                    }
                }
                catch (Exception e1)
                {
                    sbexception.AppendLine(string.Format("**  Exception occurred when writting log *** [{0}] ", e1.Message));
                }
            }
        }
        catch (Exception ex1)
        {
            sbexception.AppendLine(string.Format("**  Exception occurred when writting log *** [{0}] ", ex1.Message));
        }

        #endregion
        sbexception.AppendLine(string.Format("=================================================="));
        sbexception.AppendLine(string.Format(" Source : {0} ", ex.Source));
        sbexception.AppendLine(string.Format("=================================================="));
        sbexception.AppendLine(string.Format(" StackTrace : {0} ", ex.StackTrace));
        sbexception.AppendLine(string.Format("=================================================="));
        sbexception.AppendLine(string.Format(" TargetSite : {0} ", ex.TargetSite));
        sbexception.AppendLine(string.Format("************************************************"));
        sbexception.AppendLine(string.Format(" Finished Writting Exception info :{0} ", count));
        sbexception.AppendLine(string.Format("************************************************"));
        sbexception.AppendLine(string.Format("************************************************"));
        sbexception.AppendLine(string.Format(""));
        sbexception.AppendLine(string.Format(""));

        return sbexception.ToString();

    }
}

Below is the sample Class which uses this Utility Class

[Serializable]
    public class FlatFileItem
    {
        ArrayList errorlist = new ArrayList();

        public FlatFileItem()
        {
            if (errorlist == null) { errorlist = new ArrayList(); }
        }

        //Name of the file
        public string FileName { get; set; }
        public override string ToString()
        {
            return string.Format(@"FlatFileItem (Unzip FTPLineItem) => FileName:{0}",  this.FileName);
        }
    }


public class someclass {
    public void somemethod(){
        try{

              //Throw exception code

        } catch (Exception ex)
                    {
                        ex.Data["flatfile"] = Convert.ToString(flatfile);  //Using data property
                        flatfile.HasErrors = true;  //not there in above example
                        flatfile.Parent.AddErrorInfo(ex); //not there in above example
                        logger.Error(String.Format(ex.Message)); //not there in above example

                        throw ( new Exception ("yourmsg",ex)); //if you want to do this
                    }
    }
}
查看更多
SAY GOODBYE
4楼-- · 2019-05-10 09:12

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

Yes there is. Don't be "smart" and use ex.Message and ex.StackTrace. Just use ex.ToString(). It will recurse into inner exceptions (multiple levels if required) and show the complete stacktrace.

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

To provide a small example, this is what you get if you create an instance of a class that throws an exception in the static constructor of the class. This exception throw will be wrapped in a TypeInitializationException.

Before:

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

Not very helpful. It is hard to determine what went wrong.

After:

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

Now you can quite easily determine the root cause of the problem being a duplicate key in a dictionary and pinpoint it to line 43 in the source file.

查看更多
登录 后发表回答