如何在 Spring 引导中记录 SQL 语句?

How can I log SQL statements in Spring Boot?

我想在文件中记录 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 语句?

尝试在您的属性文件中使用它:

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

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

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

在您的 application.properties 文件中。

个人偏好设置为:

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

您可以查看这些链接以供参考:

这也适用于标准输出:

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>

根据documentation是:

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...:[=​​13=]

    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 放入 application.properties 并不总是有帮助。

您可以尝试在数据库配置的属性中添加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 OSS 框架允许您代理实际的 JDBC DataSource,如下图所示:

您可以定义 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 必须是由您在应用程序中使用的 [连接池][2] 定义的 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)]

你只需要设置 spring.jpa.show-sql=true 在 application.properties 例如你可以参考这个 https://github.com/007anwar/ConfigServerRepo/blob/master/application.yaml

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

#Enable logging for config troubeshooting
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开机版本:2.3.5.RELEASE

基本方法是在 application.properties 中添加以下行。这将使 spring 启动记录所有执行的 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 Show SQL:

#show sql statement
logging.level.org.hibernate.SQL=debug

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

您只需在 application.properties 中为标准输出 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