How to log SQL queries, their parameters and resul

2020-02-07 03:36发布

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?

1条回答
Viruses.
2楼-- · 2020-02-07 04:14

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
查看更多
登录 后发表回答