Saturday, March 15, 2008

Logging Performance Exceptions (Part 1)

You've probably wished you could find out why a certain block of code was occasionally slow in production. Wouldn't it be nice to turn on extra logging only when things were acting up? You can!

With a bit of logging in your code, you can get an output like this:

 [135ms] request share purchase
[5ms] validate purchase request
[40ms] check account balances
[39ms] synchronous balance request
[30ms] read uncommitted share availability check
[55ms] queue request
[30ms] persist message to queue
[15ms] write audit log


The oddly named hatch-timer tool, will give you a breakdown by putting simple push and pop methods in your code. It's not as fancy as doing it with AOP, but it's trivial to add.

One cool feature is configuring Hatch to only log when your code takes over a certain duration. For example, to log if businessMethod takes 1 second or longer:

   public void businessMethod() {
TimerStackUtil.enableAndPush("businessMethod");
...
TimerStackUtil.setThreadLocalMetricsLogger(
new ExceedsDurationMetricsLogger(BasicMetricsLogger.LOGGER,999));
TimerStackUtil.pop("businessMethod");


Check out the getting started to try it yourself!

5 comments:

David Dossot said...

A few years ago I wrote a similar performance monitor thingy but I decided to use an aspect for it.

I think this kind of orthogonal concerns are better fitted in an aspect, as the logging code does not fit well in the methods you intend to monitor because it relates to a different level of abstraction.

Moreover you can apply you aspects to different methods by configuration changes only...

My €.02

Idcmp said...

I agree AOP seems like a good fit for Hatch. I've added an issue to experiment with this.

I like the simplicity of the current API; an average programmer can fit it in their head along with the original problem they're trying to solve.

Derek said...

Aspects would be a good way of doing this, however, it would also frequently be a harder sell to team-leads, etc. Adding one simple library and a few calls to it, would, I think, generally be seen as less invasive, so an easier sell to the team-lead if you needed to add some logging to help diagnose a production issue.

Owen Jacobson said...

Let there be aspects:

http://www.unreasonent.com/software/com.unreasonent.hatch/hatch-spring/

Repo root: http://maven.unreasonent.com/public/

Owen Jacobson said...

Oops. I neglected to mention that the source is available for your abuse at http://hg.unreasonent.com/public/hatch-spring/.