springboot使用p6spy打印完整SQL

  • pom

平常使用orm框架的时候,虽然在spring boot配置文件上面配置过orm的打印sql语句之后,并不会真正打印出完整的sql

pom

        <!-- https://mvnrepository.com/artifact/p6spy/p6spy --><dependency><groupId>p6spy</groupId><artifactId>p6spy</artifactId><version>3.8.7</version></dependency>

数据库配置

spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver
spring.datasource.url=jdbc:p6spy:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=UTF-8&&serverTimezone=Asia/Shanghai&&allowMultiQueries=true

数据库驱动将com.mysql.jdbc.Driver替换为com.p6spy.engine.spy.P6SpyDriver,然后在url中的按上面的格式加入p6spy即可。
再在资源目录下加入spy.properties配置文件

###
# #%L
# P6Spy
# %%
# Copyright (C) 2013 P6Spy
# %%
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# #L%
###
#################################################################
# P6Spy Options File                                            #
# See documentation for detailed instructions                   #
# http://p6spy.github.io/p6spy/2.0/configandusage.html          #
#################################################################
#################################################################
# MODULES                                                       #
#                                                               #
# Module list adapts the modular functionality of P6Spy.        #
# Only modules listed are active.                               #
# (default is com.p6spy.engine.logging.P6LogFactory and         #
# com.p6spy.engine.spy.P6SpyFactory)                            #
# Please note that the core module (P6SpyFactory) can't be      #
# deactivated.                                                  #
# Unlike the other properties, activation of the changes on     #
# this one requires reload.                                     #
#################################################################
#modulelist=com.p6spy.engine.spy.P6SpyFactory,com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
################################################################
# CORE (P6SPY) PROPERTIES                                      #
################################################################
# A comma separated list of JDBC drivers to load and register.
# (default is empty)
#
# Note: This is normally only needed when using P6Spy in an
# application server environment with a JNDI data source or when
# using a JDBC driver that does not implement the JDBC 4.0 API
# (specifically automatic registration).
#driverlist=
driverlist=com.mysql.cj.jdbc.Driver
# for flushing per statement
# (default is false)
#autoflush = false
# sets the date format using Java's SimpleDateFormat routine.
# In case property is not set, miliseconds since 1.1.1970 (unix time) is used (default is empty)
#dateformat=
# prints a stack trace for every statement logged
#stacktrace=false
# if stacktrace=true, specifies the stack trace to print
#stacktraceclass=
# determines if property file should be reloaded
# Please note: reload means forgetting all the previously set
# settings (even those set during runtime - via JMX)
# and starting with the clean table
# (default is false)
#reloadproperties=false
reloadproperties=true
# determines how often should be reloaded in seconds
# (default is 60)
#reloadpropertiesinterval=60
# specifies the appender to use for logging
# Please note: reload means forgetting all the previously set
# settings (even those set during runtime - via JMX)
# and starting with the clean table
# (only the properties read from the configuration file)
# (default is com.p6spy.engine.spy.appender.FileLogger)
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
appender=com.p6spy.engine.spy.appender.StdoutLogger
#appender=com.p6spy.engine.spy.appender.FileLogger
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# name of logfile to use, note Windows users should make sure to use forward slashes in their pathname (e:/test/spy.log)
# (used for com.p6spy.engine.spy.appender.FileLogger only)
# (default is spy.log)
#logfile = spy.log
# append to the p6spy log file. if this is set to false the
# log file is truncated every time. (file logger only)
# (default is true)
#append=true
# class to use for formatting log messages (default is: com.p6spy.engine.spy.appender.SingleLineFormat)
#logMessageFormat=com.p6spy.engine.spy.appender.SingleLineFormat
#自定义日志格式,在类中定义
logMessageFormat=com.baidu.mpks.backendweb.util.P6SpyLogger
# format that is used for logging of the date/time/... (has to be compatible with java.text.SimpleDateFormat)
# (default is dd-MMM-yy)
#databaseDialectDateFormat=dd-MMM-yy
databaseDialectDateFormat=yyyy-MM-dd HH:mm:ss
# whether to expose options via JMX or not
# (default is true)
#jmx=true
# if exposing options via jmx (see option: jmx), what should be the prefix used?
# jmx naming pattern constructed is: com.p6spy(.<jmxPrefix>)?:name=<optionsClassName>
# please note, if there is already such a name in use it would be unregistered first (the last registered wins)
# (default is none)
#jmxPrefix=
#################################################################
# DataSource replacement                                        #
#                                                               #
# Replace the real DataSource class in your application server  #
# configuration with the name com.p6spy.engine.spy.P6DataSource #
# (that provides also connection pooling and xa support).       #
# then add the JNDI name and class name of the real             #
# DataSource here                                               #
#                                                               #
# Values set in this item cannot be reloaded using the          #
# reloadproperties variable. Once it is loaded, it remains      #
# in memory until the application is restarted.                 #
#                                                               #
#################################################################
#realdatasource=/RealMySqlDS
#realdatasourceclass=com.mysql.jdbc.jdbc2.optional.MysqlDataSource
#################################################################
# DataSource properties                                         #
#                                                               #
# If you are using the DataSource support to intercept calls    #
# to a DataSource that requires properties for proper setup,    #
# define those properties here. Use name value pairs, separate  #
# the name and value with a semicolon, and separate the         #
# pairs with commas.                                            #
#                                                               #
# The example shown here is for mysql                           #
#                                                               #
#################################################################
#realdatasourceproperties=port;3306,serverName;myhost,databaseName;jbossdb,foo;bar
#################################################################
# JNDI DataSource lookup                                        #
#                                                               #
# If you are using the DataSource support outside of an app     #
# server, you will probably need to define the JNDI Context     #
# environment.                                                  #
#                                                               #
# If the P6Spy code will be executing inside an app server then #
# do not use these properties, and the DataSource lookup will   #
# use the naming context defined by the app server.             #
#                                                               #
# The two standard elements of the naming environment are       #
# jndicontextfactory and jndicontextproviderurl. If you need    #
# additional elements, use the jndicontextcustom property.      #
# You can define multiple properties in jndicontextcustom,      #
# in name value pairs. Separate the name and value with a       #
# semicolon, and separate the pairs with commas.                #
#                                                               #
# The example shown here is for a standalone program running on #
# a machine that is also running JBoss, so the JDNI context     #
# is configured for JBoss (3.0.4).                              #
#                                                               #
# (by default all these are empty)                              #
#################################################################
#jndicontextfactory=org.jnp.interfaces.NamingContextFactory
#jndicontextproviderurl=localhost:1099
#jndicontextcustom=java.naming.factory.url.pkgs;org.jboss.nameing:org.jnp.interfaces
#jndicontextfactory=com.ibm.websphere.naming.WsnInitialContextFactory
#jndicontextproviderurl=iiop://localhost:900
################################################################
# P6 LOGGING SPECIFIC PROPERTIES                               #
################################################################
# filter what is logged
# please note this is a precondition for usage of: include/exclude/sqlexpression
# (default is false)
#filter=false
# comma separated list of strings to include
# please note that special characters escaping (used in java) has to be done for the provided regular expression
# (default is empty)
#include =
# comma separated list of strings to exclude
# (default is empty)
#exclude =
# sql expression to evaluate if using regex
# please note that special characters escaping (used in java) has to be done for the provided regular expression
# (default is empty)
#sqlexpression =
#list of categories to exclude: error, info, batch, debug, statement,
#commit, rollback and result are valid values
# (default is info,debug,result,resultset,batch)
#excludecategories=info,debug,result,resultset,batch
excludecategories=info,debug,result,resultset
# Execution threshold applies to the standard logging of P6Spy.
# While the standard logging logs out every statement
# regardless of its execution time, this feature puts a time
# condition on that logging. Only statements that have taken
# longer than the time specified (in milliseconds) will be
# logged. This way it is possible to see only statements that
# have exceeded some high water mark.
# This time is reloadable.
#
# executionThreshold=integer time (milliseconds)
# (default is 0)
#executionThreshold=
################################################################
# P6 OUTAGE SPECIFIC PROPERTIES                                #
################################################################
# Outage Detection
#
# This feature detects long-running statements that may be indicative of
# a database outage problem. If this feature is turned on, it will log any
# statement that surpasses the configurable time boundary during its execution.
# When this feature is enabled, no other statements are logged except the long
# running statements. The interval property is the boundary time set in seconds.
# For example, if this is set to 2, then any statement requiring at least 2
# seconds will be logged. Note that the same statement will continue to be logged
# for as long as it executes. So if the interval is set to 2, and the query takes
# 11 seconds, it will be logged 5 times (at the 2, 4, 6, 8, 10 second intervals).
#
# outagedetection=true|false
# outagedetectioninterval=integer time (seconds)
#
# (default is false)
#outagedetection=false
# (default is 60)
#outagedetectioninterval=30

com.wk.util.P6SpyLogger实现如下:

import com.p6spy.engine.spy.appender.MessageFormattingStrategy;
import org.apache.commons.lang.time.FastDateFormat;import java.util.Date;public class P6SpyLogger implements MessageFormattingStrategy {private FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss:SSS");@Overridepublic String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String jdbcUrl) {return !"".equals(sql.trim()) ? this.format.format(new Date()) + " | took " + elapsed + "ms | " + category + " | connectionId " + connectionId + "\n " + sql + "\njdbcUrl\t: " + jdbcUrl + ";" : "";}
}

最后我们可以看到完整的sql打印:

2020-12-22 16:52:57:015 | took 10ms | statement | connectionId 0select node_id from `datasource_nodeId_relation` where datasource_id =1
jdbcUrl : jdbc:p6spy:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=UTF-8&&serverTimezone=Asia/Shanghai&&allowMultiQueries=true;

springboot使用p6spy打印完整SQL相关推荐

  1. springboot整合P6spy 打印sql语句《二》

    1.加入P6spy maven依赖 <!-- https://mvnrepository.com/artifact/p6spy/p6spy --> <dependency>&l ...

  2. Hibernate 配置 p6spy 显示完整 sql 语句

    一.下载 p6spy-install包   官网:[url]http://www.p6spy.com/[/url] 拷贝 p6spy.jar 到 WEB-INF\lib\         spy.pr ...

  3. mybatis-plus配置控制台打印完整带参数SQL语句

    问题背景 通常我们开发的时候,需要联合控制台和Navicat/PLSQL等工具进行语句的拼接检查,如果只是输出了一堆???,那么将极大降低我们的效率.因此我们需要输出完整的SQL语句以便调试. Upd ...

  4. 记录druid整合springboot+logback配置打印sql日志

    [记录druid整合springboot+logback配置打印sql日志] 整合记录 整合记录 首先看 druid 的LogFilter 为我们准备的四种logger类型 这些logger分别对应打 ...

  5. SpringBoot中Mybatis打印sql日志

    application.yml中加上 # springBoot+Mybatis 控制台打印SQL语句 (方式一) logging:level:com.zoctan.api.mapper : debug ...

  6. springboot 项目输出 sql 到控制台、 SpringBoot 中 Mybatis 打印 sql

    前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家.点击跳转到教程. SpringBoot中Mybatis打印sql 如果使用的是 application.propert ...

  7. druid定义 java使用_druid 配置打印完整可执行的SQL

    druid 是支持 打印完整可以执行SQL的,只是 druid 默认不会打印.这点我觉得做得不够友好.这么好用的功能,居然默认隐藏 ? spring boot 配置 引入依赖 com.alibaba ...

  8. MybatisPlus:SQL语句打印、SQL分析、自定义主键值策略填充(IdType.INPUT)、动态表名、多租户、枚举、类型处理器、连表自定义SQL(使用wrapper)

    文章目录 1. 简单使用以及配置 - 带分页配置 2. 用法 2.0 Wrapper属性 2.1 @TableId - 自定义主键生成策略 2.2 @TableField - 自定义字段值填充 2.3 ...

  9. sql server jar包_老王,怎么完整SQL的显示日志,而不是???...

    点击蓝色"Java面试那些事儿"关注我哟 加个"星标",优质文章,第一时间送达 来源:http://1t.click/ag6q在常规项目的开发中可能最容易出问题 ...

最新文章

  1. Enhanced-RCNN: 一种高效的比较句子相似性的方法 |​WWW 2020
  2. python便捷数据怎么获取_Python数据获取与表示基础编程练习
  3. Curator-01
  4. mac 下系统目录权限问题
  5. idea 这么还原debug_看源码,我为什么推荐IDEA ?
  6. LAMP环境安装与apache配置
  7. Springboot 多模块项目创建与配置
  8. 无线网络的基础及优化方案
  9. ZFNet: Visualizing and Understanding Convolutional Networks
  10. 自定义List接口及相关方法
  11. 哪吒之魔童降世视听语言影评_《哪吒之魔童降世》影评:生而孤独,从不认命...
  12. 计算机内存体系与Java 内存模型
  13. java 一元二次方程_Java类求解一元二次方程的根
  14. 据说中国电信将ADSL的80端口给封了
  15. linux内核代码_解决Linux内核代码审阅者短缺的问题
  16. Java自定义类的属性、方法结合数组简单使用
  17. StartSSL免费SSL证书成功申请-HTTPS让访问网站更安全
  18. git push方法
  19. 《Python从入门到实践》第五章动手试一试
  20. 幂运算(快速幂)Java实现

热门文章

  1. 数字出版是个伪概念,没有钱途
  2. IJCAI-21三大奖项公布,强化学习之父、CMU助理教授方飞、德扑AI之父获奖
  3. Java毕设项目信管专业毕业生就业管理信息系统计算机(附源码+系统+数据库+LW)
  4. 蓝桥杯第十三届国赛PythonB组题解
  5. “买卖股票的最佳时机” 系列——我来教你稳赚不亏~
  6. 彩虹挂号软件设计模块详细说明
  7. 增量集成测试和非增量集成测试
  8. 通过SECRET_KEY绕过flask的session认证
  9. 网络故障,到底是交换机的问题还是网线水晶头做法问题?
  10. Android开发错误——Could not find class