When something goes wrong in a .NET application, it’s important to log sufficient information from the exception for diagnostic purposes. Here are some ideas on how to do this well.
Under pressure to deliver working code, I find it very tempting to throw a token piece of logging into place and then to move on:
The problem with this approach is that is discards information; when used correctly, a .NET exception includes a great deal of information useful for diagnostic purposes.
The first improvement is to recognise that it’s common for some frameworks to wrap exceptions to
supply context to the error. We need to be checking the
InnerException and handling this wrapping.
Since we don’t want to write the same code over and over, let’s wrap this into an extension method:
Catching and logging an exception now looks like this:
This is an improvement - but we can do better.
Every exception contains a dictionary of name/object values - we should include those in our output. ADO.NET, for example, includes details about the database connection, server version and the SQL being executed in every exception.
Again, we don’t want to write the same code over and over, so let’s create a new extension method:
With this method, we get all the detail (if any) out of the dictionary of values.
Combine the two methods together and we get the following:
For bonus credit, extend the logging framework so that we can write this:
With the implementation of
Log.Exception left as an exercise for the reader.