How to log the start and the completion of DB transactions in Hibernate

If you also want to see transaction isolation level for new created transactions:

log4j.logger.org.springframework.transaction.support.AbstractPlatformTransactionManager=debug log4j.logger.org.springframework.orm.hibernate5.HibernateTransactionManager=debug log4j.logger.org.springframework.orm.jpa.JpaTransactionManager=debug log4j.logger.org.springframework.jdbc.datasource.DataSourceTransactionManager=debug


try to set hibernate generate_statistics property

<prop key="hibernate.generate_statistics">true</prop>

and set

log4j.logger.org.hibernate=DEBUG

then you will see all hibernate logs, and you will be able to correctly choose hibernate classes to log in log4j configuration file


For Hibernate 5

  • For SLF4J logging:

    <logger name="org.hibernate.engine.transaction.internal.TransactionImpl" level="debug"/>
    
  • For Log4j:

     <logger name="org.hibernate.engine.transaction.internal.TransactionImpl">
          <level value="DEBUG"/>
     </logger>
    

For Hibernate 4

You need to set the logging threshold to DEBUG for the following classes:

  1. For JDBC transactions (e.g. RESOURCE_LOCAL)

    • For SLF4J logging:

      <logger name="org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction" level="debug"/>
      
    • For Log4j:

      <logger name="org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction">
         <level value="DEBUG"/>
      </logger>
      
  2. For JTA transactions

    • For SLF4J logging:

      <logger name="org.hibernate.engine.transaction.internal.jta.JtaTransaction" level="debug"/>
      
    • For Log4j:

      <logger name="org.hibernate.engine.transaction.internal.jta.JtaTransaction">
         <level value="DEBUG"/>
      </logger>
      

It's better to activate the DEBUG level for as few classes as possible because otherwise, your logs size will increase dramatically.


Enabling these logs may be helpful also

<logger name="org.hibernate.resource.transaction" level="debug"/>
<logger name="org.hibernate.resource.jdbc" level="debug"/>
<logger name="org.hibernate.internal.SessionImpl" level="debug"/>
<logger name="org.hibernate.internal.SessionFactoryImpl" level="debug"/>

(hibernate 5)

it prints logs about session begin/close and other relevant details

[org.hibernate.internal.SessionImpl] (default task-19) Opened Session [8c3ecbac-91b5-4dd8-b012-bfb1b4fe476c] at timestamp: 1592951456170 .....

[org.hibernate.internal.SessionImpl] (default task-19) Closing session [8c3ecbac-91b5-4dd8-b012-bfb1b4fe476c] ........ [org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl] (default task-19) Logical connection closed