在看本文之前你需要會使用logback或者log4j2基本配置,可以參看前期文章
1、druid官方出的方案,本文是在官方方案上進一步優化,Druid中使用log4j2進行日志輸出
2、在使用mybatis作為ORM組件,打印SQL日志需要指定xxxx.Mapper日志級別是DEBUG級別,因為多服務下包名是不一樣的,這樣做是比較不方便無法做到通用。
3、官方的描述中需要開啟日志打印
# 配置日志輸出
spring.datasource.druid.filter.slf4j.enabled=true
標紅的是不需要打印,查看源碼,com.alibaba.druid.filter.logging.Slf4jLogFilter
發現默認情況下都是true配置,因此我們需要將不需要打印的日志改為false
源碼
if (statementPrepareAfterLogEnable && isStatementLogEnabled()) { statementLog("{conn-" + statement.getConnectionProxy().getId() + ", pstmt-" + statement.getId() + "} created. " + statement.getSql()); }
我們將statementPrepareAfterLogEnable 配置為false即可
spring.datasource.druid.filter.slf4j.enabled=true spring.datasource.druid.filter.slf4j.statement-prepare-after-log-enabled=false
日志輸出如下,已經沒有created.
同理,closed也是如此配置,
#輸出sql日志 spring.datasource.druid.filter.slf4j.enabled=true spring.datasource.druid.filter.slf4j.statement-prepare-after-log-enabled=false spring.datasource.druid.filter.slf4j.statement-close-after-log-enabled=false
最終輸出結果
關於sql換行的問題,我DEBUG跟蹤了下,發現最原始的SQL來源於
具體追蹤到mybatis的源碼
org.apache.ibatis.mapping.MappedStatement#getBoundSql
org.apache.ibatis.scripting.xmltags.DynamicSqlSource#getBoundSql
這里就不在深究,druid官方提供的 statementLogSqlPrettyFormat 變量,看樣子是日志格式化,但是這個變量並沒有被使用。