p6spy使用

前言

  p6spy是一个开源项目,通常使用它来跟踪数据库操作,查看程序运行过程中执行的sql语句。

示例

添加依赖

<dependency>
    <groupId>p6spygroupId>
    <artifactId>p6spyartifactId>
    <version>3.7.0version>
dependency>

自定义输出格式

package cn.e3mall.common.utils;

import com.p6spy.engine.spy.appender.MessageFormattingStrategy;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * p6spy打印日志输出格式修改
 * 1.只打印最终执行的sql.
 * 2.sql换到下一行
 * 3.结尾处增加分号,以标示sql结尾
 * Created by odelia on 2016/1/4.
 */
public class P6SpyLogger implements MessageFormattingStrategy {
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");

    public String formatMessage(int connectionId, String now,
                         long elapsed, String category, String prepared, String sql) {
        if (!sql.trim().equals("")) {
            return format.format(new Date()) + " | took " + elapsed + "ms | " 
                + category + " | connection " + connectionId + "\n " + sql + ";";
        }
        return "";
    }
}

新建spy.properties

reloadproperties=true
appender=com.p6spy.engine.spy.appender.Slf4JLogger
#P6SpyLogger 类全路径名
logMessageFormat=cn.e3mall.common.utils.P6SpyLogger
databaseDialectDateFormat=yyyy-MM-dd hh:mm:ss
excludecategories=info,debug,result,resultset

修改数据库配置文件

<bean id="dataSource" class="com.p6spy.engine.spy.P6DataSource">
    <constructor-arg>
        <ref bean="dataSourceDefault">ref>
    constructor-arg>
bean>
<bean id="dataSourceDefault" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
    ........
bean>

在log4j.properties中添加配置

##p6spy
log4j.logger.p6spy=info,spyConsole
log4j.appender.spyConsole = org.apache.log4j.ConsoleAppender
log4j.appender.spyConsole.Target=System.out
log4j.appender.spyConsole.layout = org.apache.log4j.PatternLayout
log4j.appender.spyConsole.layout.ConversionPattern = #####-----%m%n

控制台打印效果

p6spy使用_第1张图片


GitHub地址: https://github.com/p6spy/p6spy
参考资料: https://blog.csdn.net/kwy15732621629/article/details/77924398
参考资料: https://www.cnblogs.com/luodengxiong/p/6766357.html

你可能感兴趣的:(Java)