Snippets: Java: Spring: Log SQLs Generated by JDBCTemplate

 20th August 2020 at 2:19pm

怎样在 SpringBoot 应用中把 JDBCTemplate 执行时的 SQL 语句、参数值打印出来?

在配置中把 org.springframework.jdbc.core.JdbcTemplate 的 log 等级调成 debug,如:

logging:
  file: /data/logs/tsf/${spring.application.name}/${spring.application.name}
  level:
    org.springframework.jdbc.core: trace

效果:

Executing prepared SQL statement [select HEADLINE_TEXT, NEWS_DATE_TIME from MY_TABLE where PRODUCT_KEY = ? and NEWS_DATE_TIME between ? and ? order by NEWS_DATE_TIME]
Setting SQL statement parameter value: column index 1, parameter value [aaa], value class [java.lang.String], SQL type unknown
Setting SQL statement parameter value: column index 2, parameter value [Thu Oct 11 08:00:00 CEST 2012], value class [java.util.Date], SQL type unknown
Setting SQL statement parameter value: column index 3, parameter value [Thu Oct 11 08:00:10 CEST 2012], value class [java.util.Date], SQL type unknown

参考