且构网

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

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

更新时间:2021-07-19 00:40:52

JDBC 日志记录

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

例如,当我们在应用程序中执行一些 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'

其结果为表格形式:

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

要使用这个 starter,我们必须将它的依赖添加到我们的项目中:

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