詳解druid打印SQL日志


在看本文之前你需要會使用logback或者log4j2基本配置,可以參看前期文章

log4j2    logback

 

1、druid官方出的方案,本文是在官方方案上進一步優化,Druid中使用log4j2進行日志輸出

2、在使用mybatis作為ORM組件,打印SQL日志需要指定xxxx.Mapper日志級別是DEBUG級別,因為多服務下包名是不一樣的,這樣做是比較不方便無法做到通用。

3、官方的描述中需要開啟日志打印

# 配置日志輸出
spring.datasource.druid.filter.slf4j.enabled=true

 

image

 

標紅的是不需要打印,查看源碼,com.alibaba.druid.filter.logging.Slf4jLogFilter

 

image

發現默認情況下都是true配置,因此我們需要將不需要打印的日志改為false

image

 

源碼

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.

image

 

 

同理,closed也是如此配置,

image

 

#輸出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

 

最終輸出結果

image

 

 

關於sql換行的問題,我DEBUG跟蹤了下,發現最原始的SQL來源於

image

具體追蹤到mybatis的源碼

org.apache.ibatis.mapping.MappedStatement#getBoundSql

image

org.apache.ibatis.scripting.xmltags.DynamicSqlSource#getBoundSql

image

這里就不在深究,druid官方提供的 statementLogSqlPrettyFormat 變量,看樣子是日志格式化,但是這個變量並沒有被使用。

image


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM