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


当前回答

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

许多人通过在测试继承层次结构中某处声明的@TestPropertySources注释来声明自定义测试时属性。这将覆盖您在应用程序中输入的任何内容。属性或其他生产属性设置,以便在测试时有效地忽略您正在设置的那些值。

其他回答

请使用:

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

根据文档,它是:

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

我们可以在应用程序中使用其中任何一个。属性文件:

spring.jpa.show-sql=true

例子:

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

or

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_

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

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=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>