Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log SQL queries, their parameters and results with Log4jdbc in Spring Boot projects?

To view SQL queries sent to DB we usually use showSql parameter:

spring.jpa.showSql=true

It allows us to see the statement body but not its parameters:

insert into master (id, version, name) values (null, ?, ?)

And especially we don't see a result of the query.

Is there a way to see SQL statement, its parameters and result in the application log?

like image 234
Cepr0 Avatar asked Jan 30 '23 21:01

Cepr0


1 Answers

JDBC logging

With log4jdbc-spring-boot-starter we can easily log all JDBC statements, their parameters and results in Spring Boot/Spring Data JPA projects.

For example, when we perform some JPQL query in our application:

select u from User u where u.name = 'john'

then we see the following SQL query with its parameter in the application log:

select ... from users users0_ where users0_.name='john'

And its result in the table form:

|---|---------|
|id |name     |
|---|---------|
|1  |john     |
|---|---------|

To use this starter we have to add its dependency to our project:

<dependency>
    <groupId>com.integralblue</groupId>
    <artifactId>log4jdbc-spring-boot-starter</artifactId>
    <version>1.0.2</version>
</dependency>

and add these parameters to application.properties:

logging.level.jdbc.resultsettable=info
logging.level.jdbc.sqltiming=info
logging.level.jdbc.sqlonly=fatal
logging.level.jdbc.audit=fatal
logging.level.jdbc.resultset=fatal
logging.level.jdbc.connection=fatal

Additionally, we can add these log4jdbc parameters to get the output in one line:

log4jdbc.dump.sql.addsemicolon=true
log4jdbc.dump.sql.maxlinelength=0
log4jdbc.trim.sql.extrablanklines=false
like image 186
Cepr0 Avatar answered Feb 01 '23 18:02

Cepr0