如何在Spring Boot中记录SQL语句?

我想把SQL语句记录到一个文件中。

我在application.properties中有以下属性:

spring.datasource.url=...
spring.datasource.username=user
spring.datasource.password=1234
spring.datasource.driver-class-name=net.sourceforge.jtds.jdbc.Driver


spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true


security.ignored=true
security.basic.enabled=false


logging.level.org.springframework.web=INFO
logging.level.org.hibernate=INFO
logging.file=c:/temp/my-log/app.log

当我运行程序时,

cmd> mvn spring-boot:run

我可以在控制台中看到SQL语句,但它们不会出现在app.log中。该文件只包含Spring的基本日志。

我应该怎么做才能在日志文件中看到SQL语句?

538396 次浏览

试着在你的属性文件中使用这个:

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

对于SQL Server驱动程序(Microsoft SQL Server JDBC驱动程序),尝试使用:

logging.level.com.microsoft.sqlserver.jdbc=debug

在你的应用中。属性文件。

我个人的偏好是设置:

logging.level.com.microsoft.sqlserver.jdbc=info
logging.level.com.microsoft.sqlserver.jdbc.internals=debug

你可以参考以下链接:

  • 跟踪驱动程序操作
  • < a href = " https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html howto。7. logging" rel="nofollow noreferrer"> " How-to " Guides,日志< / >

这也适用于标准输出:

spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.use_sql_comments=true
spring.jpa.properties.hibernate.format_sql=true

记录值:

logging.level.org.hibernate.type=trace

只需将此添加到application.properties

这适用于我(YAML):

spring:
jpa:
properties:
hibernate:
show_sql: true
format_sql: true
logging:
level:
org:
hibernate:
type: trace

如果你有一个logback-spring.xml文件或类似的文件,添加以下代码:

<logger name="org.hibernate.SQL" level="trace" additivity="false">
<appender-ref ref="file" />
</logger>

这对我很有用。

获取绑定变量:

<logger name="org.hibernate.type.descriptor.sql" level="trace">
<appender-ref ref="file" />
</logger>

根据文档,它是:

spring.jpa.show-sql=true # Enable logging of SQL statements.

请使用:

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE
spring.jpa.show-sql=true

如果要查看实际使用的参数,可以使用查询

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql=TRACE

然后注意,实际的参数值显示为binding parameter

    2018-08-07 14:14:36.079 DEBUG 44804 --- [           main] org.hibernate.SQL                        : select employee0_.id as id1_0_, employee0_.department as departme2_0_, employee0_.joining_date as joining_3_0_, employee0_.name as name4_0_ from employee employee0_ where employee0_.joining_date=?
2018-08-07 14:14:36.079 TRACE 44804 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [TIMESTAMP] - [Tue Aug 07 00:00:00 SGT 2018]

我们可以在application.properties文件中使用其中任何一个:

spring.jpa.show-sql=true

例子:

//Hibernate: select country0_.id as id1_0_, country0_.name as name2_0_ from country country0_

logging.level.org.hibernate.SQL=debug

例子:

2018-11-23 12:28:02.990 DEBUG 12972 --- [nio-8086-exec-2] org.hibernate.SQL   : select country0_.id as id1_0_, country0_.name as name2_0_ from country country0_

翻译接受的答案YAML工作为我

logging:
level:
org:
hibernate:
SQL:
TRACE
type:
descriptor:
sql:
BasicBinder:
TRACE

如果您在使用此设置时遇到了问题,并且它似乎有时有效而其他时候无效——请考虑它是否在单元测试期间不起作用。

许多人通过在测试继承层次结构中声明的@TestPropertySources注释来声明自定义测试时属性。这将覆盖你在application.properties或其他生产属性设置中设置的任何值,这样你设置的那些值在测试时将被有效地忽略。

spring.jpa.properties.hibernate.show_sql=true放入应用程序。属性并不总是有帮助。

您可以尝试将properties.put("hibernate.show_sql", "true");添加到数据库配置的属性中。

public class DbConfig {


@Primary
@Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean
entityManagerFactory(
EntityManagerFactoryBuilder builder,
@Qualifier("dataSource") DataSource dataSource
) {
Map<String, Object> properties = new HashMap();
properties.put("hibernate.hbm2ddl.auto", "validate");
properties.put("hibernate.show_sql", "true");


return builder
.dataSource(dataSource)
.packages("com.test.dbsource.domain")
.persistenceUnit("dbsource").properties(properties)
.build();
}

登录到标准输出

添加到application.properties

### To enable
spring.jpa.show-sql=true


### To make the printing SQL beautify
spring.jpa.properties.hibernate.format_sql=true

这是打印SQL查询的最简单方法,但它不会记录准备好的语句的参数。

不推荐使用,因为它不是优化的日志框架。

使用日志框架

添加到application.properties

### Logs the SQL queries
logging.level.org.hibernate.SQL=DEBUG
### Logs the prepared statement parameters
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE


### To make the printing SQL beautify
spring.jpa.properties.hibernate.format_sql=true

通过指定上述属性,日志条目将被发送到已配置的日志追加器,例如log-back或Log4j

要避免的设置

你不应该使用这个设置:

spring.jpa.show-sql=true

show-sql的问题是SQL语句是打印在控制台中,所以没有办法过滤它们,就像你通常用日志框架做的那样。

使用Hibernate日志记录

在日志配置文件中,如果添加了以下日志:

<logger name="org.hibernate.SQL" level="debug"/>

然后,Hibernate将在创建JDBC PreparedStatement时打印SQL语句。这就是为什么使用参数占位符记录语句的原因:

INSERT INTO post (title, version, id) VALUES (?, ?, ?)

如果你想记录绑定参数值,只需要添加以下记录器:

<logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="trace"/>

一旦你设置了BasicBinder记录器,你会看到绑定参数值也被记录下来:

DEBUG [main]: o.h.SQL - insert into post (title, version, id) values (?, ?, ?)
TRACE [main]: o.h.t.d.s.BasicBinder - binding parameter [1] as [VARCHAR] - [High-Performance Java Persistence, part 1]
TRACE [main]: o.h.t.d.s.BasicBinder - binding parameter [2] as [INTEGER] - [0]
TRACE [main]: o.h.t.d.s.BasicBinder - binding parameter [3] as [BIGINT] - [1]

使用datasource-proxy

datasource-proxy OSS框架允许你代理实际的JDBC DataSource,如下图所示:

DataSource-Proxy

你可以这样定义Hibernate使用的dataSource bean:

@Bean
public DataSource dataSource(DataSource actualDataSource) {
SLF4JQueryLoggingListener loggingListener = new SLF4JQueryLoggingListener();
loggingListener.setQueryLogEntryCreator(new InlineQueryLogEntryCreator());
return ProxyDataSourceBuilder
.create(actualDataSource)
.name(DATA_SOURCE_PROXY_NAME)
.listener(loggingListener)
.build();
}

注意,actualDataSource必须是你在应用程序中使用的连接池定义的DataSource

接下来,你需要在你的日志框架配置文件中将net.ttddyy.dsproxy.listener日志级别设置为debug。例如,如果你正在使用Logback,你可以添加以下记录器:

<logger name="net.ttddyy.dsproxy.listener" level="debug"/>

一旦你启用了datasource-proxy, SQL语句将被记录如下:

Name:DATA_SOURCE_PROXY, Time:6, Success:True,
Type:Prepared, Batch:True, QuerySize:1, BatchSize:3,
Query:["insert into post (title, version, id) values (?, ?, ?)"],
Params:[(Post no. 0, 0, 0), (Post no. 1, 0, 1), (Post no. 2, 0, 2)]

你只需要在application.properties中设置spring.jpa.show-sql=true

例如,你可以引用ConfigServerRepo/application.yaml

在文件application.properties中使用以下代码:

# Enable logging for configuration troubleshooting
logging.level.org.hibernate.SQL=DEBUG
logging.level.com.zaxxer.hikari.HikariConfig=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

在我的YAML文件:

logging:
level:
org.hibernate.SQL: DEBUG
org.hibernate.type.descriptor.sql: TRACE

Spring Boot版本:2.3.5.RELEASE

基本的方法是在application.properties中添加以下行。这将使Spring Boot能够记录所有执行的SQL查询:

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

第二行用于美化SQL语句。

如果你想使用记录器,你可以使用以下几行:

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

第二行用于打印与查询绑定的所有参数。

将这些添加到属性中。引用Hibernate显示SQL:

# Show SQL statement
logging.level.org.hibernate.SQL=debug


# Show SQL values
logging.level.org.hibernate.type.descriptor.sql=trace

您可以简单地在应用程序中添加以下行。属性为stdout SQL查询:

spring.jpa.properties.hibernate.show_sql=true

如果您正在使用JdbcTemplate,在application.properties文件中添加以下内容来记录SQL和参数值。

logging.level.org.springframework.jdbc.core.JdbcTemplate=DEBUG
logging.level.org.springframework.jdbc.core.StatementCreatorUtils=TRACE
在Spring引导中,我们可以使用两种方法记录SQL语句: 1:使用记录仪 2: standard approach


< >强记录器 您应该将这一行添加到应用程序中。属性文件:< / p >

logging.level.org.hibernate.SQL=DEBUG

< >强标准方法 你应该在应用程序中添加这些行。属性文件:< / p >

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

对于hibernate 6: 它是:< / p >

spring.jpa.properties.hibernate.show_sql=true
logging.level.org.hibernate.orm.jdbc.bind = trace