views:

35

answers:

1
+3  Q: 

Logging in DBCP

I'm using Apache Commons DBCP. There is a task to track the inner behavior of the DBCP - number of active and idle connections.

I found out that DBCP lacks any such logging at all. Yes, tt is possible to write the code that outputs the status of the BasicDataSource when connection is borrowed from the pool. However there is no way to track the status of the BasicDataSource when connection is returned or closed, because connection object knows nothing about the pool.

Any ideas?

+1  A: 

I think aspects may be the solution to your quandry. Check out:

Basically, you can write an aspect or two that will "latch onto" the execution of some methods inside DBCP.

Something like:

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;

@Aspect
public class AroundExample {

  @Around("org.apache.commons.dbcp.PoolingDataSource.getConnection()")
  public Object doBasicPStuff(ProceedingJoinPoint pjp) throws Throwable {
    // write code to do what you want
    final PoolingDataSource ds = (PoolingDataSource) pjp.getThis();
    // log whatever you want

    // let it finish
    Object retVal = pjp.proceed();
    // stop stopwatch
    return retVal;
  }

}

That's just a tiny example. Aspects are really powerful and there's a bunch of different ways to do what you want. The code depends on whether you're using Spring or not, and what exactly you wanna log.

P.S. I haven't tested the above code.

The Alchemist