How can you log sql queries executed by Hibernate?

ghz 9months ago ⋅ 149 views

You can log SQL queries executed by Hibernate by configuring logging for the Hibernate framework. Hibernate uses a logging framework such as Log4j or SLF4J for logging, so you need to configure the logging level for Hibernate SQL statements to be recorded.

Here's how you can configure logging for Hibernate SQL queries using Log4j as an example:

  1. Add Logging Dependencies: Ensure that you have the necessary logging dependencies in your project. For Log4j, you would need to include the Log4j library in your project's dependencies.

  2. Configure Log4j Properties: Create or modify the log4j.properties file in your project's resources directory. Add or modify the configuration to include logging for Hibernate SQL queries. Here's an example configuration:

    # Root logger option
    log4j.rootLogger=INFO, stdout, file
    
    # Hibernate SQL logging
    log4j.logger.org.hibernate=INFO
    log4j.logger.org.hibernate.SQL=DEBUG
    log4j.logger.org.hibernate.type.descriptor.sql=TRACE
    
    # Console output appender
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
    
    # File output appender
    log4j.appender.file=org.apache.log4j.RollingFileAppender
    log4j.appender.file.File=logs/application.log
    log4j.appender.file.MaxFileSize=5MB
    log4j.appender.file.MaxBackupIndex=10
    log4j.appender.file.layout=org.apache.log4j.PatternLayout
    log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
    

    In this configuration:

    • log4j.logger.org.hibernate.SQL=DEBUG sets the logging level for Hibernate SQL statements to DEBUG. You can adjust the level to INFO or TRACE as needed.
    • log4j.appender.stdout and log4j.appender.file define the appenders for console and file output respectively.
    • Adjust the ConversionPattern to customize the log message format according to your preferences.
  3. Ensure Log4j Configuration is Loaded: Ensure that Log4j is properly configured and loaded by your application. This typically involves initializing Log4j at application startup, such as in a servlet context listener or a Spring boot configuration.

  4. Run the Application: Once configured, run your application. Hibernate SQL queries, along with their parameters and execution times, will be logged according to the configured logging level.

By following these steps and adjusting the logging configuration as needed, you can effectively log SQL queries executed by Hibernate in your application.