1、pom依赖
<!-- https://mvnrepository.com/artifact/com.github.gavlyukovskiy/p6spy-spring-boot-starter -->
<dependency>
<groupId>com.github.gavlyukovskiy</groupId>
<artifactId>p6spy-spring-boot-starter</artifactId>
<version>1.9.0</version>
</dependency>
2、yaml配置
注意:驱动要换成p6spy
spring:
datasource:
driver-class-name: com.p6spy.engine.spy.P6SpyDriver
url: jdbc:p6spy:h2:mem:testdb
username: sa
password: sa
decorator:
datasource:
enabled: true # 是否启用
p6spy:
log-format: yyyy-MM-dd HH:mm:ss.SSS
log-file: p6spy.log # 日志文件路径
logging: slf4j
3、P6Spy的配置
在resources新建文件spy.properties
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
# 1、logMessageFormat=com.p6spy.engine.spy.appender.SingleLineFormat
# 2、logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat
# customLogMessageFormat=%(currentTime) | SQL use time: %(executionTime) ms | connect info: %(category)-%(connectionId) | execute sql: %(sql)
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,commit,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
#driverlist=org.h2.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2
4、自定义sql打印日志
上面的配置是P6Spy内置的SQL输出格式,我们也可以自定义自己的SQL日志打印格式:
public class P6SPYConfig implements MessageFormattingStrategy {
@Override
public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String url) {
Map<String, Object> message = new LinkedHashMap<>(8);
String newPrepared = prepared.replace(" ", "").replace("\n", " ");
message.put("prepared", newPrepared);
String newSql = sql.replace(" ", "").replace("\n", " ");
message.put("sql", newSql);
return JSONObject.toJSONString(message, true);
}
}
5、官方文档
配置文档:https://p6spy.readthedocs.io/en/latest/configandusage.html
github:https://github.com/p6spy/p6spy