SpringBoot如何打印带参数的sql和执行时间-p6spy

SpringBoot如何打印带参数的sql和执行时间-p6spy

背景:最近优化项目,然后有找影响效率的地方,就像打印所有sql日志

然后发现了mybatisplus的这个插件 

前言
如果你恰好使用 Mybatis-plus 框架,那么在开发环境就不能错过它提供的 PerformanceInterceptor 插件,该插件能打印 sql 执行时间以及完整的 sql 语句,非常方便复制出来分析 sql

使用
使用的 Mybatis-plus 框架比较老,是 2.3 版本的,引入依赖,然后实例化 PerformanceInterceptor 插件即可(注意该插件在 3.2 版本以上被移除,可考虑使用 p6spy 分析插件),如下

3.2以下

<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>2.3</version>
            <exclusions>
                <exclusion>
                    <artifactId>tomcat-jdbc</artifactId>
                    <groupId>org.apache.tomcat</groupId>
                </exclusion>
            </exclusions>
</dependency>

  


@Bean
@Profile({"dev", "test"})
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(15000);
performanceInterceptor.setFormat(false);
return performanceInterceptor;

  

3.2以上用P6Spy插件

软件简介
P6Spy是一个可以用来在应用程序中拦截和修改数据操作语句的开源框架。 通过P6Spy我们可以对SQL语句进行拦截,相当于一个SQL语句的记录器,这样我们可以用它来作相关的分析,比如性能分析。

P6SPY提供了如下几个功能:

记录SQL语句的执行时间戳。
记录SQL语句类型
记录SQL填入参数的和没有填入参数的SQL语句
根据配置的时间控制SQL语句的执行时间,对超出时间的SQL语句输出到日志文件中

展示效果
可以看到打印的sql,执行时间,和打印sql所携带的参数

 

如何配置
1.在Pom文件中添加maven依赖

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

  



2.新增文件spy.properties


#日志格式
appender=com.p6spy.engine.spy.appender.Slf4JLogger
#输出格式
logMessageFormat=com.p6spy.engine.spy.appender.MultiLineFormat
#sql执行时间和格式
customLogMessageFormat=executionTime:%(executionTime) | sql:%(sql)
官网有相应的配置文件和参数说明,以上只是常用的几个配置属性
Configuration and Usage — p6spy 3.9.2-SNAPSHOT documentation

  

3.修改mysql连接驱动
数据库的驱动替换为:com.p6spy.engine.spy.P6SpyDriver

url的jdbc后面加: p6spy:

driver-class-name: com.p6spy.engine.spy.P6SpyDriver
url: jdbc:p6spy:mysql://localhost:3306/studyx_briliansolution6?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC

具体配置如下:

spring:
datasource:
driver-class-name: com.p6spy.engine.spy.P6SpyDriver
# url: jdbc:mysql://localhost:3306/studyx_briliansolution6?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
url: jdbc:p6spy:mysql://localhost:3306/studyx_briliansolution6?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC

posted @ 2022-06-24 10:46  逐星i  阅读(930)  评论(0编辑  收藏  举报