我想把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语句?


当前回答

对于hibernate 6: 它是:

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

其他回答

这也适用于标准输出:

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。

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

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

然后注意,实际的参数值显示为绑定参数…:

    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]

如果您正在使用JdbcTemplate,请在应用程序中添加以下内容。属性文件记录SQL和参数值。

logging.level.org.springframework.jdbc.core.JdbcTemplate=DEBUG
logging.level.org.springframework.jdbc.core.StatementCreatorUtils=TRACE

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

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

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

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

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

我个人的偏好是设置:

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

你可以参考以下链接:

跟踪驱动程序操作 “如何”指南,7。日志记录