如何在 Spring Boot 项目中使用 Log4jdbc 记录 SQL 查询及其参数和结果? [英] How to log SQL queries, their parameters and results with Log4jdbc in Spring Boot projects?
问题描述
查看发送到数据库的SQL查询我们通常使用showSql
参数:
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.
有没有办法在应用程序日志中看到SQL语句、它的参数和结果?
Is there a way to see SQL statement, its parameters and result in the application log?
推荐答案
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
这篇关于如何在 Spring Boot 项目中使用 Log4jdbc 记录 SQL 查询及其参数和结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!