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


当前回答

如果您正在使用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

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

spring.jpa.properties.hibernate.show_sql=true

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

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

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

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

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

在应用程序中添加spring.jpa.properties.hibernate.show_sql=true。属性并不总是有帮助。

您可以尝试添加properties.put(“hibernate。show_sql”、“真正的”);到数据库配置的属性。

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();
    }