Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...