Logging SQL statements in a Spring Boot application can be useful for debugging and performance analysis. You can achieve this by configuring the data source and using the logging capabilities of your chosen database provider. Here, I’ll provide an example for a Spring Boot application using Hibernate and MySQL.
1. Include Logging Dependencies
Make sure you have the necessary logging dependencies in your project. For example, if you’re using Maven, include the following dependencies:
<dependencies>
<!-- Spring Boot Starter Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Logback (Logging Framework) -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
</dependencies>
2. Configure Logging in application.properties or application.yml
Add the following configuration properties to your application.properties or application.yml file:
# Logging SQL statements (Hibernate)
spring.jpa.show-sql=true
logging.level.org.hibernate.SQL=debug
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=trace
The spring.jpa.show-sql=true property enables the logging of SQL statements, and the logging.level.org.hibernate.SQL=debug property sets the log level for Hibernate SQL statements to debug. Adjust these properties based on your logging preferences. Finally If you want to log values too use logging.level.org.hibernate.type.descriptor.sql.BasicBinder=trace.
