Pages

Sunday, April 8, 2012

Hibernate SQL Logging to Log4j

In my projects, for logging the SQL statements generated by Hibernate I always set the hibernate.sql_show property to true in the hibernate.cfg.xml file:
true
This logs the SQL statements to the STDOUT console. Only recently I realized that the logs can also be sent to Log4j. Of course this allows to log the SQL statements not only to the STDOUT but also to all possible Log4j appenders such as a file appender etc.. There are (at least) two ways to do this.

1) Setting the log level statically in the log4j.properties configuration file, e.g.:
log4j.logger.org.hibernate.SQL=DEBUG, FILE_APPENDER
log4j.additivity.org.hibernate.SQL=false
Setting additivity to false ensures that log messages aren't bubbled up to parent handlers.

2) Or setting the log level dynamically in Java, e.g.:
import org.apache.log4j.Logger;
import org.apache.log4j.Level;

...    

Logger log = Logger.getLogger("org.hibernate.SQL");
log.setLevel(Level.DEBUG);

No comments:

Post a Comment