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


当前回答

如果你有一个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>

其他回答

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

spring.jpa.properties.hibernate.show_sql=true

对于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。

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

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

在文件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