In my new ‘old’ project which I just inherited there is – once more – Hibernate and plain JDBC access to a database, happily mixed. Hibernate logs SQL nicely, but that leaves out whatever datbase access the rest of the application is performing.
I found log4jdbc very convenient which allows fain-grained logging over every interaction with a jdbc connection. It works by wrapping the JDBC driver which your application would use normally. This works fine for stand-alone applications or web applications which bring their own database connectivity code, but it doesn’t work out of the box for container-managed datasources because the JDBC driver is already loaded before log4jdbc can wrap it.
There are two solutions:
1. Use datasources. In this mode, your application gets the datasource from the container and wraps it with a log4jdbc datasource. In the application I’m working on that does not work since legacy code is directly obtaining the database connection via obscure channels (i.e. accessing the java naming context and bypassing any IOC framework), so…
2. Install log4jdbc into the servlet container classloader. For tomcat that’s the /lib directory of the application server. I also needed the slf4j-api, slf4j-log4j and log4j jars which I’m sure at some point I will regret because of classloading issues with the web application which uses the same jars. But this is only for debugging a particular issue, so this setup does not go into production.