maven項目導入jar包
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
<version>3.7.0</version>
</dependency>
編寫P6SpyConfig類
package com.example.demo.P6Spy;
import com.p6spy.engine.spy.P6DataSource;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import javax.sql.DataSource;
@Configuration
public class P6SpyConfig {
/**
* P6數據源包裝, 打印SQL語句
*/
@Bean
public P6DataSourceBeanPostProcessor p6DataSourceBeanPostProcessor() {
return new P6DataSourceBeanPostProcessor();
}
class P6DataSourceBeanPostProcessor implements BeanPostProcessor, PriorityOrdered {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof DataSource) {
return new P6DataSource((DataSource) bean);
}
return bean;
}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
}
}
配置spy.properties文件
# 是否自動刷新 默認 flase #autoflush=false # 日期格式 dateformat=yyyy-MM-dd HH:mm:ss # 監測屬性配置文件是否進行重新加載 reloadproperties=true # 屬性配置文件重新加載的時間間隔,單位:秒 默認60s reloadpropertiesinterval=60 # 使用日志系統記錄sql appender=com.p6spy.engine.spy.appender.Slf4JLogger # 自定義日志打印 logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat customLogMessageFormat=%(executionTime)ms | %(sqlSingleLine) # date類型字段記錄日志時使用的日期格式 默認dd-MMM-yy databaseDialectDateFormat=yyyy-MM-dd HH:mm:ss # boolean類型字段記錄日志時使用的日期格式 默認boolean 可選值numeric databaseDialectBooleanFormat=boolean # 是否通過jmx暴露屬性 默認true jmx=true # 是否開啟日志過濾 默認false, 這項配置是否生效前提是配置了 include/exclude/sqlexpression filter=true # 過濾 Log 時所排除的表名列表,以逗號分隔 默認為空 exclude=Z020_LOG_RESOURCE,Z020_LOG_OPERATE # 配置記錄Log例外 excludecategories=info,debug,result,batc,resultset
運行結果

成功打印了sql語句在控制台。
