A JDBC Query Monitor

Categories: Java

I recently wrote a Java JDBC wrapper for monitoring calls to a database (JDBC DataSource). My employer has allowed this to be released as open source.

It’s pretty simple; one primary class (which uses dynamic proxy generation) and a few helpers. Plus unit-tests, etc.

Class QueryMonitor implements the standard javax.sql.DataSource interface, and delegates to an underlying DataSource object - ie acts as a Proxy. When Statement/PreparedStatement/CallableStatement objects created via this proxy are actually “executed”, info about the call is passed to registered “reporter” objects (aka listeners).

The code provides functionality similar to log4jdbc aka jdbc-spy. However:

  • the code is simpler than log4jdbc
  • configuration does not rely on race-prone and functionally-limited static fields

An application using this code is responsible for wrapping datasources to be monitored; this is easiest when the application is using dependency-injection of some kind.

The source can be found on this site or on github. I have no intention to publish this as a library; if you find the code useful, just copy it into your project.