Spring Boot JDBC Template SQL Log

2022-09-03 08:57:24

我正在尝试使用Spring Boot JDBC的参数来记录SQL查询,但它没有在日志中打印详细信息。我使用的是Spring Boot 1.5.8版本。请帮我解决这个问题。

应用程序.属性:

spring.datasource.url=url
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver

logging.level.org.springframework.jdbc.core.JdbcTemplate=debug

spring.datasource.type = com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.connection-timeout=60000
spring.datasource.hikari.maximum-pool-size=2

存储 库:

@Repository
public class DataRepository {
    private static Logger log = LoggerFactory.getLogger(DataRepository.class);

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    public Data findDataObjet() throws Exception {

        Map<String, Object> parameters = new HashMap<>();
        parameters.put("id1", "mike");
        parameters.put("id2", new Long(1));

        String sqlString = "select * from table1 where id1 = ":id" and id2 = :id2";
        log.info("Query:" + sqlString);//this log is printing

        Data extObj = jdbcTemplate.query(sqlString, parameters, (rs) -> {
            if (rs != null && rs.next()) {
                Data innerObj = new Data();
                innerObj.setName(rs.getString("name"));             
                return innerObj;
            } else {
                log.info("No records found:"+rs);
                return null;
            }
        });

        return extObj;

    }
}

日志回弹簧.xml:

<appender name="dailyRollingFileAppender"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <FileNamePattern>${logsPath}DATA%d{MMddyyyy}.log
        </FileNamePattern>
        <maxHistory>4</maxHistory>
    </rollingPolicy>

    <encoder>
        <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level
            %logger{35}-%msg %n</Pattern>
    </encoder>
</appender>
<root level="INFO">
    <appender-ref ref="dailyRollingFileAppender" />
</root>


答案 1

尝试

log4j.category.org.springframework.jdbc.core = TRACE

上述语句还将使用入站参数打印 SQL 查询。

如果您只需要记录查询,请使用以下内容

log4j.category.org.springframework.jdbc.core = DEBUG

您可以使用以下命令在日志回复文件中启用

<logger name="org.springframework.jdbc.core.JdbcTemplate">
  <level value="debug" />
</logger>

<logger name="org.springframework.jdbc.core.StatementCreatorUtils">
  <level value="debug" />
</logger>

更新:对于 Springboot 2.x,它将是

logging.level.org.springframework.jdbc.core=TRACE

谢谢朱国威!


答案 2

将以下内容添加到属性文件也有效:

logging.level.org.springframework.jdbc.core = TRACE

推荐