Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 613
dfrankow Avatar asked Mar 10 '26 19:03

dfrankow


1 Answers

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.

like image 166
dfrankow Avatar answered Mar 12 '26 11:03

dfrankow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!