且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Spring Boot项目中使用Log4jdbc记录SQL查询,其参数和结果?

更新时间:2021-10-07 00:46:50

JDBC日志记录

使用 log4jdbc-spring-boot-starter 我们可以轻松地记录所有JDBC语句,它们的参数和结果到Spring Boot/Spring Data JPA项目中.

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.

例如,当我们在应用程序中执行一些JPQL查询时:

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

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

然后,我们在应用程序日志中看到以下SQL查询及其参数:

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>

并将这些参数添加到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

此外,我们可以添加以下 log4jdbc 参数以在一行中获得输出:

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