SQL 语句拦截框架 P6Spy 的介绍使用
P6Spy 介绍
P6Spy 是一个可以用来在应用程序中拦截和修改数据操作语句的开源框架。
通过 P6Spy 我们可以对 SQL 语句进行拦截,相当于一个 SQL 语句的记录器,这样我们可以用它来作相关的分析,比如性能分析。
- 文档:https://p6spy.readthedocs.io/
- GitHub:https://github.com/p6spy/p6spy
依赖引入
<!-- https://mvnrepository.com/artifact/p6spy/p6spy -->
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
<version>3.9.1</version>
</dependency>
P6Spy 参数
formatMessage 参数
- connectionId:连接数据库的 ID
- now:当前 time 的毫秒数
- elapsed:操作完成所需的时间(以毫秒为单位)
- category:操作的类别
- prepared:将所有绑定变量替换为实际值的 SQL 语句
- SQL:执行的 sql 语句
- url:执行 sql 语句的数据库 URL
使用 P6Spy
引入 P6Spy 的依赖。
更换数据库连接驱动。
数据库驱动将 com.mysql.jdbc.Driver 替换为 com.p6spy.engine.spy.P6SpyDriver,然后在 url 中的按下面的格式加入 p6spy 即可。
# 更换前 spring.datasource.second.driverClassName=com.mysql.cj.jdbc.Driver spring.datasource.second.jdbc-url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC # 更换后 spring.datasource.second.driverClassName=com.p6spy.engine.spy.P6SpyDriver spring.datasource.second.jdbc-url=jdbc:p6spy:mysql://127.0.0.1:3306/test?serverTimezone=UTC
添加配置文件
spy.properties
。# 单行日志 logMessageFormat=com.p6spy.engine.spy.appender.SingleLineFormat # 使用Slf4J记录sql appender=com.p6spy.engine.spy.appender.Slf4JLogger # 是否开启慢SQL记录 outagedetection=true # 慢SQL记录标准,单位秒 outagedetectioninterval=2 #日期格式 dateformat=yyyy-MM-dd HH:mm:ss
效果如下:
com.p6spy.engine.spy.appender.SingleLineFormat
单行日志:
2020-12-28 14:17:44.493 INFO 87484 --- [ main] p6spy : 2020-12-28 14:17:44|11|statement|connection 19|url jdbc:p6spy:mysql://127.0.0.1:3306/test?serverTimezone=UTC|SELECT id,author,description,title FROM book WHERE (author >= ?)|SELECT id,author,description,title FROM book WHERE (author >= 'author0')
com.p6spy.engine.spy.appender.MultiLineFormat
多行日志:
2020-12-28 14:24:00.087 INFO 42092 --- [ main] p6spy : #2020-12-28 14:24:00 | took 11ms | statement | connection 19| url jdbc:p6spy:mysql://127.0.0.1:3306/test?serverTimezone=UTC
SELECT id,author,description,title FROM book
WHERE (author >= ?)
SELECT id,author,description,title FROM book
WHERE (author >= 'author0');
自定义输出格式
在 spy.properties
配置文件中进行配置:
# 自定义输出格式
logMessageFormat=com.jueee.config.P6SpyLogger
其中,P6SpyLogger 类的实现如下:
import com.p6spy.engine.spy.appender.MessageFormattingStrategy;
import java.text.SimpleDateFormat;
import java.util.Date;
public class P6SpyLogger 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) {
return !"".equals(sql.trim()) ? this.format.format(new Date()) + " | took " + elapsed + "ms | " + category + " | connection " + connectionId + "\n " + sql + ";" : "";
}
}
执行结果如下:
2020-12-28 14:39:27.947 INFO 102272 --- [ main] p6spy : 2020-12-28 14:39:27:947 | took 11ms | statement | connection 19
SELECT id,author,description,title FROM book
WHERE (author >= 'author0');
相关文章