springboot集成p6spy实现打印sql并监控执行时间

在项目中使用mybatis打印的sql参数使用?代替,不方便阅读,使用p6spy可以将sql返回成想要的样子 1.导入依赖

<dependency>
    <groupId>p6spy</groupId>
    <artifactId>p6spy</artifactId>
    <version>3.8.5</version>
</dependency>

2.修改application.properties中的数据库驱动和url

#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#spring.datasource.url=jdbc:mysql://localhost:3306/db?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=true
#更换为com.p6spy.engine.spy.P6SpyDriver
spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver
spring.datasource.url=jdbc:p6spy:mysql://localhost:3306/data?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=true
spring.datasource.username=root
spring.datasource.password=123456

3.在application.properties同级目录下创建spy.properties配置文件

# 开启模块sql记录和长时sql记录
module.log=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.agsun.mes3f.config.P6spySqlFormatConfig
#logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat
# 自定义sql输出格式
#customLogMessageFormat=%(currentTime) | TIME\uFF1A %(executionTime) ms | SQL\uFF1A %(sql)
# 使用日志系统记录sql
appender=com.p6spy.engine.spy.appender.StdoutLogger
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
#appender=com.p6spy.engine.spy.appender.FileLogger
#logfile=spy.log
#append=true
# 配置记录Log例外
excludecategories=info,debug,result,batch,resultset
# 设置使用p6spy driver来做代理
deregisterdrivers=true
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动
driverlist=com.microsoft.sqlserver.jdbc.SQLServerDriver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 秒
outagedetectioninterval=2

4.自定义sql输出

import com.p6spy.engine.spy.appender.MessageFormattingStrategy;
import com.fkzd.common.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;

/**
 * 自定义 p6spy sql输出格式
 *
 */
public class P6spySqlFormatConfig 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) ? DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", new Date())
            + " | 耗时 " + elapsed + " ms | SQL 语句:" + StringUtils.LF + sql.replaceAll("[\\s]+", StringUtils.SPACE) + ";" : "";
    }
}

执行效果

cf0e1efed79045888f627c27a14618fb.png


已有 0 条评论

    感谢参与互动!