ORM tools can be extremely powerful and save us a lot of the mundane heavy lifting required to persist data captured in an object graph through to an RDBMS. However, one problem can be that behind the scenes the tool may not always function as expected. What’s often important is to be able to see exactly what SQL the ORM tool is building and issuing to your database.
Recently we’d switched to the Logback framework for our logging and I wanted to be able to capture all the SQL that Hibernate was generating for me. There is a Hibernate configuration property which controls whether or not the generated SQL is printed to the console:
hibernate.format_sql
Setting this property to true will print out the generated SQL to the console. However, I’ve found having a separate log file that was solely responsible for capturing this generated SQL was invaluable. So how do we set it up with Logback?
<appender name="hibernate-sql" class="ch.qos.logback.core.FileAppender">
<file>logs/hibernate-sql.log</file>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</layout>
</appender>
<logger name="org.hibernate.SQL">
<appender-ref ref="hibernate-sql"/>
</logger
This will put all our generated SQL statements from Hibernate into the hibernate-sql.log file.
