Logging application exceptions is like getting a new muffler. It isn’t exciting. It isn’t very fulfilling. It just costs time and money.
Also, it is something that needs to be done.
So, can we make exception logging as frictionless as possible?
- Roll your own logging library.
- Repeat the same code a lot in your application calling your library.
Kidding. On both fronts.
Extending Exception
Since the problem is just about logging exceptions, adding an extension method to the basic Exception class makes a lot of sense.
1: public static void Log( this Exception exception )
2: {
3: . . .
4: }
Now, using this extension method, logging an exception looks like this:
1: try
2: {
3: // do something that would throw
4: // an exception
5: }
6: catch (Exception ex)
7: {
8: ex.Log();
9: }
Enterprise Library Logging Application Block
Enterprise Library makes what happens inside the extension method an easy implementation, too. The act of logging is simple enough with EntLib, but the real value is in how the configuration story lets an application administrator decide how the logging solution will actually behave at runtime.
For instance, when building a recent application, I asked the client if they wanted to receive email when a significant application error occurred. Their response was, “Just write to the Windows Event log. We have a monitoring application that will email us.”
Fine by me! Windows Event log, text file, email, it’s all the same because the ultimate destination of the log message is a configuration setting.
Anyway, the implementation of the extension method can look as simple as this.
1: public static void Log( this Exception exception )
2: {
3: var entry = new LogEntry
4: {
5: Severity = TraceEventType.Warning,
6: Title = "Application Exception",
7: Message = exception.ToString(),
8: };
9: Logger.Write(entry);
10: }
Of course, I ended up with some overloads and other niceties , but the basic approach remains sound.
It would be better if you were using the Enterprise Library Exception Handling block for your extension method. Something like this:
try
{
}
catch(Exception ex)
{
if(!ex.Handle(“MyExceptionPolicyName”))
throw; //not handled or configured to throw
}
Then the extension method:
public static bool Handle(this Exception ex, string policyName)
{
Exception newEx = null;
bool rethrow = ExceptionPolicy.HandleException(ex, policyName, out newEx);
if (rethrow && newEx == null)
return false;
else if (rethrow && newEx != null)
throw newEx;
return true;
}