p6spy 整合springboot

发布时间 2023-04-11 23:25:13作者: 纵情95

1.导入pom

<!-- sql代理拦截,慢sql打印 -->
<dependency>
    <groupId>p6spy</groupId>
    <artifactId>p6spy</artifactId>
    <version>3.9.1</version>
</dependency>

2.配置自定义日志

import com.p6spy.engine.common.P6Util;
import com.p6spy.engine.spy.appender.MessageFormattingStrategy;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;

@Slf4j
public class P6spyConnfig implements MessageFormattingStrategy {
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");

    @Override
    public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String url) {
        StringBuilder sb = new StringBuilder();

//        JSONObject json = new JSONObject();
//        json.put("level", "ERROR");
//        json.put("time", elapsed + " ms");
//        json.put("sql", P6Util.singleLine(sql));
        sb
//            .append("{")
//            .append("连接id:").append(connectionId).append("\n")
            .append("当前时间:").append(now).append(" | ")
//            .append("类别:").append(category).append("\n")
            .append("花费时间:").append(elapsed)
            .append("毫秒 | ")
//            .append("花费时间:").append(elapsed).append("\n")
//                .append("url:").append(url).append("\n")
//            .append("预编译sql:").append(P6Util.singleLine(prepared)).append("\n")
//            .append("最终执行的sql:").append(P6Util.singleLine(sql))
            .append("超时慢sql:").append(P6Util.singleLine(sql));
//        if (elapsed > 1000) {
//            log.error("sql超时!" + sb.toString());
//        }

//            .append("}");
        return sb.toString();
    }
}

3.配置数据库连接

#mysql
spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver
spring.datasource.jdbc-url=jdbc:p6spy:mysql://localhost:3306/giov?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2b8&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=123456

4.配置spy文件

module.log=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印  控制台打印
#logMessageFormat=com.wjy.log.P6SpyLogger
#logMessageFormat=com.p6spy.engine.spy.appender.SingleLineFormat
#logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat
logMessageFormat=com.xxx.config.P6spyConnfig
# 使用日志系统记录sql  控制台打印的格式
#系统格式 输出到文件
appender=com.p6spy.engine.spy.appender.FileLogger
#appender=com.p6spy.engine.spy.appender.FileLogger
## 配置记录Log例外
excludecategories=info,debug,result,batc,resultset
# 指定 Log 的文件名 默认 spy.log
#logfile=spy1.log
# 指定是否每次是增加 Log,设置为 false 则每次都会先进行清空 默认true
append=false
# 设置使用p6spy driver来做代理
deregisterdrivers=true
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动
driverlist=com.mysql.jdbc.Driver
## log模块专属参数,当log模块开启式,如果执行语句超出这个时间(单位毫秒),才能被记录在文件中
#executionthreshold=10
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 秒   超过这个时间这个查询操作将会被中止,并且抛出异常!
outagedetectioninterval=2