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?
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.
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
Below is the sample Class which uses this Utility Class
Yes there is. Don't be "smart" and use
ex.Message
andex.StackTrace
. Just useex.ToString()
. It will recurse into inner exceptions (multiple levels if required) and show the complete stacktrace.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:
Not very helpful. It is hard to determine what went wrong.
After:
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.