阅读完需:约 10 分钟
P6Spy是一个框架,它可以无缝地拦截和记录数据库活动,而无需更改现有应用程序的代码。一般我们使用的比较多的是使用p6spy打印我们最后执行的sql语句。常用的数据框架也会自带打印sql的功能,比如jpa,mybatis等,但是一般都会有缺陷,比如打印的sql是不带执行参数拼接的sql,这种sql不完整,不具有直接可执行性。所以,p6spy就派上用场了。常见集成p6spy的方式是在资源目录下新增spy.properties配置文件,然后通过驱动装载。这种方式已经非常简单易用了,但是还有更简单的方式,通过spring boot autoconfig的特性,可以做到自动装配。
通过集成 P6Spy 到你的 Java 应用程序中,你可以:
- 监视 SQL 查询:P6Spy 可以记录所有执行过的 SQL 查询及其参数,帮助你追踪到低效或有问题的查询。
- 度量性能:它提供了详细的性能统计数据,包括每个查询的执行时间、总时间、平均时间等,从而帮助你发现瓶颈并优化数据库操作。
- 日志和审计:P6Spy 的日志功能允许你在指定的日志文件中记录所有的数据库交互信息,以便进行后期分析和审计。
- 调试应用程序:当遇到与数据库相关的错误时,P6Spy 提供了丰富的诊断信息,使得问题定位更加容易。
以下是 P6Spy 的一些主要特点:
- 易于集成:P6Spy 支持多种主流的 JDBC 驱动程序,并且可以通过简单的配置步骤将其集成到现有的 Java 应用程序中。
- 高度可定制化:你可以通过自定义日志格式和规则,根据实际需求调整输出的信息内容和样式。
- 支持多种数据库:P6Spy 兼容多种流行的数据库系统,包括 MySQL、Oracle、PostgreSQL 等。
- 线程安全:P6Spy 的设计充分考虑了多线程环境下的安全性,确保在并发情况下也能正确地收集和处理数据。
安装P6Spy
https://p6spy.readthedocs.io/en/latest/index.html
https://github.com/p6spy/p6spy
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
<version>3.9.2</version>
</dependency>
接下来,需要在application.yml
或application.properties
中进行相应的配置。
- 替换你的JDBC Driver为
com.p6spy.engine.spy.P6SpyDriver
- 在原来url jdbc:后面添加p6spy:如:
jdbc:p6spy:mysql://127.0.0.1:3306
- 添加p6spy的配置文件
spy.properties
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
username: ${env.pg_user}
password: ${env.pg_passwd}
url: jdbc:p6spy:postgresql://${env.pg_host}:${env.pg_port_write}/${env.pg_name}?currentSchema=safety&useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf8
driver-class-name: com.p6spy.engine.spy.P6SpyDriver
简单的配置
module.log=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.p6spy.engine.spy.appender.SingleLineFormat
#logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat
#customLogMessageFormat=%(currentTime) | SQL耗时: %(executionTime) ms | 连接信息: %(category)-%(connectionId) | 执行语句: %(sql)
# 使用控制台记录sql
appender=com.p6spy.engine.spy.appender.StdoutLogger
## 配置记录Log例外
excludecategories=info,debug,result,batc,resultset
# 设置使用p6spy driver来做代理
deregisterdrivers=true
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动
driverlist=com.mysql.jdbc.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 秒
outagedetectioninterval=2
spy.properties详细说明
# 指定应用的日志拦截模块,默认为com.p6spy.engine.spy.P6SpyFactory
#modulelist=com.p6spy.engine.spy.P6SpyFactory,com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 真实JDBC driver , 多个以 逗号 分割 默认为空
#driverlist=
# 是否自动刷新 默认 flase
#autoflush=false
# 配置SimpleDateFormat日期格式 默认为空
#dateformat=
# 打印堆栈跟踪信息 默认flase
#stacktrace=false
# 如果 stacktrace=true,则可以指定具体的类名来进行过滤。
#stacktraceclass=
# 监测属性配置文件是否进行重新加载
#reloadproperties=false
# 属性配置文件重新加载的时间间隔,单位:秒 默认60s
#reloadpropertiesinterval=60
# 指定 Log 的 appender,取值:
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
#appender=com.p6spy.engine.spy.appender.StdoutLogger
#appender=com.p6spy.engine.spy.appender.FileLogger
# 指定 Log 的文件名 默认 spy.log
#logfile=spy.log
# 指定是否每次是增加 Log,设置为 false 则每次都会先进行清空 默认true
#append=true
# 指定日志输出样式 默认为com.p6spy.engine.spy.appender.SingleLineFormat , 单行输出 不格式化语句
#logMessageFormat=com.p6spy.engine.spy.appender.SingleLineFormat
# 也可以采用 com.p6spy.engine.spy.appender.CustomLineFormat 来自定义输出样式, 默认值是%(currentTime)|%(executionTime)|%(category)|connection%(connectionId)|%(sqlSingleLine)
# 可用的变量为:
# %(connectionId) connection id
# %(currentTime) 当前时间
# %(executionTime) 执行耗时
# %(category) 执行分组
# %(effectiveSql) 提交的SQL 换行
# %(effectiveSqlSingleLine) 提交的SQL 不换行显示
# %(sql) 执行的真实SQL语句,已替换占位
# %(sqlSingleLine) 执行的真实SQL语句,已替换占位 不换行显示
#customLogMessageFormat=%(currentTime)|%(executionTime)|%(category)|connection%(connectionId)|%(sqlSingleLine)
# date类型字段记录日志时使用的日期格式 默认dd-MMM-yy
#databaseDialectDateFormat=dd-MMM-yy
# boolean类型字段记录日志时使用的日期格式 默认boolean 可选值numeric
#databaseDialectBooleanFormat=boolean
# 是否通过jmx暴露属性 默认true
#jmx=true
# 如果jmx设置为true 指定通过jmx暴露属性时的前缀 默认为空
# com.p6spy(.<jmxPrefix>)?:name=<optionsClassName>
#jmxPrefix=
# 是否显示纳秒 默认false
#useNanoTime=false
# 实际数据源 JNDI
#realdatasource=/RealMySqlDS
# 实际数据源 datasource class
#realdatasourceclass=com.mysql.jdbc.jdbc2.optional.MysqlDataSource
# 实际数据源所携带的配置参数 以 k=v 方式指定 以 分号 分割
#realdatasourceproperties=port;3306,serverName;myhost,databaseName;jbossdb,foo;bar
# jndi数据源配置
# 设置 JNDI 数据源的 NamingContextFactory。
#jndicontextfactory=org.jnp.interfaces.NamingContextFactory
# 设置 JNDI 数据源的提供者的 URL。
#jndicontextproviderurl=localhost:1099
# 设置 JNDI 数据源的一些定制信息,以分号分隔。
#jndicontextcustom=java.naming.factory.url.pkgs;org.jboss.naming:org.jnp.interfaces
# 是否开启日志过滤 默认false, 这项配置是否生效前提是配置了 include/exclude/sqlexpression
#filter=false
# 过滤 Log 时所包含的表名列表,以逗号分隔 默认为空
#include=
# 过滤 Log 时所排除的表名列表,以逗号分隔 默认为空
#exclude=
# 过滤 Log 时的 SQL 正则表达式名称 默认为空
#sqlexpression=
#显示指定过滤 Log 时排队的分类列表,取值: error, info, batch, debug, statement,
#commit, rollback, result and resultset are valid values
# (默认 info,debug,result,resultset,batch)
#excludecategories=info,debug,result,resultset,batch
# 是否过滤二进制字段
# (default is false)
#excludebinary=false
# P6Log 模块执行时间设置,整数值 (以毫秒为单位),只有当超过这个时间才进行记录 Log。 默认为0
#executionThreshold=
# P6Outage 模块是否记录较长时间运行的语句 默认false
# outagedetection=true|false
# P6Outage 模块执行时间设置,整数值 (以秒为单位)),只有当超过这个时间才进行记录 Log。 默认30s
# outagedetectioninterval=integer time (seconds)
使用内置自定义格式化器(CustomLineFormat
)手动配置打印格式
- 修改配置文件的格式化为自定义格式化
logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat
自己创建类实现MessageFormattingStrategy
接口重写formatMessage
方法即可
public class P6SpyLogger implements MessageFormattingStrategy {
/**
* @Desc: 重写日志格式方法
* now:当前时间
* elapsed:执行耗时
* category:执行分组
* prepared:预编译sql语句
* sql:执行的真实SQL语句,已替换占位
*/
@Override
public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql) {
return !"".equals(sql.trim()) ? "[ " + LocalDateTime.now() + " ] --- | took "
+ elapsed + "ms | " + category + " | connection " + connectionId + "\n "
+ sql + ";" : "";
}
}
- 将配置文件中的格式化器属性改为自己的类
logMessageFormat=com.xxx.xxx.P6SpyLogger
Spring Boot集成
https://github.com/gavlyukovskiy/spring-boot-data-source-decorator
对于Spring Boot项目,可以使用p6spy-spring-boot-starter
来简化集成过程。
对于 Spring Boot 2 应用程序,最新兼容版本是 1.8.1
<dependency>
<groupId>com.github.gavlyukovskiy</groupId>
<artifactId>p6spy-spring-boot-starter</artifactId>
<version>1.9.1</version>
</dependency>
所有类型的 beanJdbcEventListener
均在 P6Spy 中注册:
@Bean
public JdbcEventListener myListener() {
return new JdbcEventListener() {
@Override
public void onAfterGetConnection(ConnectionInformation connectionInformation, SQLException e) {
System.out.println("got connection");
}
@Override
public void onAfterConnectionClose(ConnectionInformation connectionInformation, SQLException e) {
System.out.println("connection closed");
}
};
}
通过添加RuntimeListenerSupportFactory
到 P6Spy 中来实现的modulelist
,覆盖此属性将导致不注册工厂,因此不会应用监听器
简单示例
decorator:
datasource:
p6spy:
logging: file
log-format: "\n current:%(currentTime) || time:%(executionTime) ms || %(category)-%(connectionId) || sql:%(sqlSingleLine)\n "
# 自定义日志类
log-file: ${LOGPATH:./logs/safetySQL.log}
打印拦截结果
current:1720163480592 || time:3 ms || statement-0 || sql:update controller_deploy set method_name = 'update', logging = 0, annotate = '分析对象#修改' where id = 0
可以在您的配置中配置小组参数application.properties
:
# Register P6LogFactory to log JDBC events
decorator.datasource.p6spy.enable-logging=true
# Use com.p6spy.engine.spy.appender.MultiLineFormat instead of com.p6spy.engine.spy.appender.SingleLineFormat
decorator.datasource.p6spy.multiline=true
# Use logging for default listeners [slf4j, sysout, file, custom]
decorator.datasource.p6spy.logging=slf4j
# Log file to use (only with logging=file)
decorator.datasource.p6spy.log-file=spy.log
# Class file to use (only with logging=custom). The class must implement com.p6spy.engine.spy.appender.FormattedLogger
decorator.datasource.p6spy.custom-appender-class=my.custom.LoggerClass
# Custom log format, if specified com.p6spy.engine.spy.appender.CustomLineFormat will be used with this log format
decorator.datasource.p6spy.log-format=
# Use regex pattern to filter log messages. If specified only matched messages will be logged.
decorator.datasource.p6spy.log-filter.pattern=
Springboot也支持配置文件spy.properties
读取配置的关键代码
在项目启动的时候会去读取配置文件spy.properties和yml里面的配置,两个都读取,spy.properties的配置优先级更高,当spy.properties里面没有的时候再启用yml的配置