# 数据库执行语句打印、性能分析框架(p6Spy 的使用)
# 概述
我们在调式程序难免要输出执行 sql 语句,可是使用 Mybatis 或者 JPA 等框架时,打印的的 sql 总是带着
?占位符,不能直接在数据库执行并且不够直观。所以迫切需要一款专注打印可执行的 SQL 及执行时间的 sql 打印、性能分析框架p6Sql。
# 一、p6spy
# 1、介绍
p6spy 是一个开源项目,通常使用它来跟踪数据库操作,查看程序运行过程中执行的 sql 语句。
官网地址:p6spy 官网
# 2、原理
p6spy 将应用的数据源给劫持了,应用操作数据库其实在调用 p6spy 的数据源,p6spy 劫持到需要执行的 sql 或者 hql 之类的语句之后,它自己去调用一个 realDatasource,再去操作数据库。
# 3、应用场景
p6spy 可以输出日志到文件中,控制台, 或者传递给 Log4j,而且还能配搭 SQL Profiler 或 IronTrackSQL 图形化监控 SQL 语句,监测到哪些语句的执行是耗时的,逐个优化。
# 二、使用
# 1、引入依赖
| <dependency> | |
| <groupId>p6spy</groupId> | |
| <artifactId>p6spy</artifactId> | |
| <version>3.9.1</version> | |
| </dependency> | 
# 2、配置文件修改
- 替换你的 JDBC Driver 为 com.p6spy.engine.spy.P6SpyDriver
- 在原来 url jdbc: 后面添加 p6spy:。如:jdbc:p6spy:mysql://127.0.0.1:3306
或jdbc:p6spy:oracle:thin:@localhost:1521:ORCL- 添加 p6spy 的配置文件 spy.properties
# 3、简单的 spy.properties
| 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 | 
上面的的 logMessageFormat 是打印的格式 SingleLineFormat 最基础的配置是不会打印 sql 的。如果修改有两种方式:
# 1、使用内置自定义格式化器 ( CustomLineFormat ) 手动配置打印格式
使用示例:
- 修改配置文件的格式化为自定义格式化 logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat
- 配置文件中添加手动配置打印的格式,推荐示例:customLogMessageFormat=%(currentTime) | SQL 耗时: %(exceutionTime) ms | 连接信息: %(category)-%(connectionld) | 执行语句: %(sql)
# 2、自己创建类实现 MessageFormattingStrategy 接口重写 formatMessage 方法即可
使用示例:
- 创建类 P6SpyLogger
| 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
# p6spy 有 3 种日志输出方式
#(推荐)使用Slf4j输出 配合SpringBoot使用日志门面
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 仅控制台输出
#appender=com.p6spy.engine.spy.appender.StdoutLogger
# 文件输出,使用内置日志输出到文件
#appender=com.p6spy.engine.spy.appender.FileLogger
# 附录: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) | 
