4

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.