我想把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=TRACE
spring.jpa.show-sql=true

其他回答

根据文档,它是:

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

基本的方法是在application.properties中添加以下代码行。这将使Spring Boot能够记录所有执行的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

第二行用于打印与查询绑定的所有参数。

在应用程序中添加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();
    }

登录到标准输出

添加到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。