Spring Boot
Hibernate
Logback
SQL Logging
Java Configuration

Can't avoid hibernate logging SQL to console with Spring Boot and Logback

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Spring Boot offers a powerful way to build Java-based applications with custom configurations and dependencies aggregated in one place. However, logging SQL statements generated by Hibernate, the popular ORM framework employed in many Spring Boot applications, can be tricky—especially if you're trying to suppress it altogether. This article provides a technical overview, including some common scenarios and potential solutions around Hibernate SQL logging in Spring Boot applications using Logback as a logging framework.

Understanding Logback and Spring Boot Integration

Logback is a popular logging framework for Java applications, offering features similar to Log4j but with considerably faster execution. In Spring Boot, Logback is the default logging implementation, and it is configured using `logback-spring.xml` or `logback.xml`. For developers who want to adjust logging levels or completely disable logging for certain packages, Logback provides flexible configurations.

The Hibernate SQL Logging Dilemma

Hibernate often logs SQL statements to the console for operations involving database interaction. While essential during development, these logs can become noise in a production environment. The challenge is to effectively suppress these logs without affecting other logging behaviors.

Common Reasons for Hibernate SQL Logging Issues

  1. Configuration Overrides: Spring Boot’s `application.properties` can set Hibernate logging options, but external configurations like `logback.xml` might overwrite them.
  2. Misconfigured Logging Levels: Hibernate logs SQL statements at the `DEBUG` level. If the logging level for Hibernate packages is set incorrectly, SQL statements may appear unexpectedly in the logs.
  3. Console Appender Settings: The default console appender in Logback might be improperly configured, causing all `DEBUG` level logs, including Hibernate statements, to appear.

Configuring Hibernate Logging

Below, we explore potential solutions to mitigate or eliminate Hibernate SQL logs from appearing in your console.

Solution 1: Adjust `application.properties`

Spring Boot provides properties that directly control Hibernate’s SQL logging:

  • Configure the logger for the `org.hibernate.SQL` package to suppress SQL output by setting its level to `WARN`.
  • The configuration for `org.hibernate.type.descriptor.sql.BasicBinder` suppresses parameter-binding display.
  • A standard console appender, set to log `INFO` level and above, ensures SQL statements won't appear.

Course illustration
Course illustration

All Rights Reserved.