p6spy 简单使用

最近开发中用到 spring-data-jpa + hibernate 的持久层框架,在调试过程中,日志记录的hibernate SQL执行语句无法显示传入的参数,所以上github上搜索了一番,发现了p6spy这个框架,此框架能够无缝地拦截和记录数据库的执行语句,而不会对现有应用程序进行代码更改。下面介绍一下p6spy的简单配置和使用。

源码

https://github.com/p6spy/p6spy

导包

http://mvnrepository.com/artifact/p6spy/p6spy

<dependency>
    <groupId>p6spy</groupId>
    <artifactId>p6spy</artifactId>
    <version>3.7.0</version>
</dependency>
配置

1、复制源码中 p6spy/src/main/assembly/individualFiles/spy.properties 文件到Maven项目的resource目录下
2、根据需要配置 spy.properties 选项值

#项目数据库驱动
driverlist=com.mysql.jdbc.Driver
#日期格式
dateformat=yyyy-MM-dd HH:mm:ss
#sql输出样式(此为我自定义的)
logMessageFormat=com.p6spy.engine.spy.appender.PrettySqlMultiLineFormat

#sql输出方式
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
appender=com.p6spy.engine.spy.appender.StdoutLogger
#appender=com.p6spy.engine.spy.appender.FileLogger

3、项目数据源配置
jdbc.driver 替换为 com.p6spy.engine.spy.P6SpyDriver
jdbc.url 替换为 jdbc:p6spy:mysql:/xxx

问题

1、原生的sql语句样式是单行的,如何格式化
改动源码,创建一个类自定义输出格式,重新打包发布到自己的本地库

package com.p6spy.engine.spy.appender;

import org.hibernate.engine.jdbc.internal.BasicFormatterImpl;
import org.hibernate.engine.jdbc.internal.Formatter;

/**
 * 优化sql输出格式,采用hibernate的 Formatter
 */
public class PrettySqlMultiLineFormat implements MessageFormattingStrategy {

    private static final Formatter formatter;

    static {
        formatter = new BasicFormatterImpl();
    }

  /**
   * Formats a log message for the logging module
   *
   * @param connectionId the id of the connection
   * @param now          the current ime expressing in milliseconds
   * @param elapsed      the time in milliseconds that the operation took to complete
   * @param category     the category of the operation
   * @param prepared     the SQL statement with all bind variables replaced with actual values
   * @param sql          the sql statement executed
   * @return the formatted log message
   */
    @Override
    public String formatMessage(final int connectionId, final String now, final long elapsed, final String category, final String prepared, final String sql) {
      return "\n#" + now + " | took " + elapsed + "ms | " + category + " | connection " + connectionId + formatter.format(sql) +";";
    }
}

spy.properties 中 logMessageFormat=com.p6spy.engine.spy.appender.PrettySqlMultiLineFormat

2、与日志框架的结合
我项目的日志框架是 slf4j + log4j2 的组合,不需要改动日志配置,p6spy可以无缝结合。

3、精简配置
如果只是自己开发调试时用,可以对p6spy定制,从github上下载源码,直接把spy.properties放到源码项目的resource目录下进行配置,然后发布到本地Maven库中,项目要用时只要在pom.xml中引入依赖就,修改数据库驱动和地址,不需要在项目中配置spy.properties文件了。
这里写图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值