Logging exceptions without crufty code: a comparison of strategies
Continue Reading January 7th, 2009 Brian Gray
You get in to work, grab a cup of coffee, and start your day with a nice, simple, easy-to-read method that stores a value object in the database. By lunch, it has ballooned to 8 lines of code, most of which handle exceptional cases, and make sure that maintenance developers can handle them in testing and production. In this post, I will describe four approaches that I have seen for minimizing this problem and describe some pros and cons for each. The four approaches are, in no particular order:
* Aspect-Oriented Programming (AOP): define an advice class that gets executed whenever any method throws an exception. Log the exception in the advice.
* The catch-all method (i.e. highest interface/tier logging): Log no exceptions at lower levels and allow all runtime exceptions to bubble up. At the highest tier (such as a web UI, main executable, Web Service, etc.), catch all exceptions and log them.
* Self-logging exceptions: Define a base exception class that logs itself in the constructor (takes a message and possibly a Class as parameters). All exceptions in the application must extend from this base class (3rd party or library exceptions must be caught and re-thrown), but no application code should ever log an exception.
* Developer logging: As above, each developer logs exceptions as they see fit.