一、簡介:
p6Spy通過劫持JDBC驅動,在調用實際`JDBC`驅動前攔截調用的目標語,達到`SQL`語句日志記錄的目的。
它包括`P6Log`和`P6Outage`兩個模塊。
P6Log 用來攔截和記錄任務應用程序的 JDBC 語句
P6Outage 專門用來檢測和記錄超過配置條件里時間的 SQL 語句
二、使用步驟:
1.導入pom
<!-- 控制台 SQL日志打印插件 --> <dependency> <groupId>p6spy</groupId> <artifactId>p6spy</artifactId> <version>3.8.1</version> </dependency>
2.在 spy.properties中指定p6spy配置
# 使用日志系統記錄 sql appender=com.p6spy.engine.spy.appender.Slf4JLogger # 自定義日志打印 logMessageFormat=cc.mrbird.febs.common.configure.P6spySqlFormatConfigure # 是否開啟慢 SQL記錄 outagedetection=true # 慢 SQL記錄標准 2 秒 outagedetectioninterval=2 # 開啟過濾 filter=true # 包含 QRTZ的不打印 exclude=QRTZ,select 1
import cc.mrbird.febs.common.utils.DateUtil; import com.p6spy.engine.spy.appender.MessageFormattingStrategy; import org.apache.commons.lang3.StringUtils; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /** * SQL格式化輸出 */ public class P6spySqlFormatConfigure implements MessageFormattingStrategy { /** * sql格式化輸出 */ @Override public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String url) { return StringUtils.isNotBlank(sql) ? formatFullTime(LocalDateTime.now(), DateUtil.FULL_TIME_SPLIT_PATTERN) + " | 耗時 " + elapsed + " ms | SQL 語句:" + StringUtils.LF + sql.replaceAll("[\\s]+", StringUtils.SPACE) + ";" : StringUtils.EMPTY; } /** * 日期格式化 */ public String formatFullTime(LocalDateTime localDateTime, String pattern) { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern); return localDateTime.format(dateTimeFormatter); } }
4、編寫application.yml配置文件
spring: datasource: dynamic: # 是否開啟 SQL日志輸出,生產環境建議關閉,有性能損耗 p6spy: true hikari: connection-timeout: 30000 max-lifetime: 1800000 max-pool-size: 15 min-idle: 5 connection-test-query: select 1 pool-name: FebsHikariCP # 配置默認數據源 primary: base datasource: # 數據源-1,名稱為 base base: username: root password: 13037489030 driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/febs_base?characterEncoding=UTF-8
三、結語:
每次訪問數據庫都對打印一條sql