dfrankow
dfrankow

Reputation: 21377

How to log a stack trace whenever Hibernate issues a SQL query?

Log a stack trace in Java:

new Throwable.printStackTrace()

To see SQL statements issued by Hibernate, set show_sql to true.

However, how do I log a stack trace every time a SQL query is issued? I'd like to use this for performance monitoring (i.e. find which parts of our source code generate the most queries).

I looked at interceptors and event listeners, and none of them seem to give a hook at the query level.

I also looked through the source (SQLStatementLogger, Loader) somewhat. I don't see any hooks.

I could perhaps try a logging jdbc driver, but it's unclear to me if the stack of the caller would be preserved properly.

I could rewrite byte code, but that seems excessive.

Edit: I could also try AspectJ to advise the SQL executing methods.

Has anyone done this? What's the best way?

Upvotes: 4

Views: 1981

Answers (1)

dfrankow
dfrankow

Reputation: 21377

I ended up attaching a new log Appender to the org.hibernate.SQL logger used by org.hibernate.jdbc.util.SQLStatementLogger (and no other class) in Hibernate 3.6.8.

Logger logger = Logger.getLogger("org.hibernate.SQL");
org.apache.log4j.rolling.RollingFileAppender appender =
    new org.apache.log4j.rolling.RollingFileAppender();
appender.setLayout(new SqlLogLayout());
// .. set appender options ..
appender.activateOptions();
logger.addAppender(appender);

Then in my SqlLogLayout I can get the stack trace, and the SQL I get from the log message.

Upvotes: 2

Related Questions