使用P6Spy格式化SQL语句

缺乏、安全感 2022-06-08 00:13 529阅读 0赞

公司最近在做一个项目,开发过程中遇到点小问题,查询结果出不来,查看自带日志打印,有点不爽,特别是想复制sql语句到数据库navicat中去调试时,还要手动复制参数值,很是麻烦,那如果想打印出格式化的详细sql语句,我们该如何做呢?

一、pom.xml文件中添加依赖:

  1. <dependency>
  2. <groupId>p6spy</groupId>
  3. <artifactId>p6spy</artifactId>
  4. </dependency>

二、在profiles下的local和dev中加入spy.properties文件,配置自定义输出格式:
主要是指定数据库驱动(日期格式化、使用单行还是多行),指定输出方式控制台、log文件等)

  1. ###
  2. # #%L
  3. # P6Spy
  4. # %%
  5. # Copyright (C) 2013 P6Spy
  6. # %%
  7. # Licensed under the Apache License, Version 2.0 (the "License");
  8. # you may not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. # #L%
  19. ###
  20. #################################################################
  21. # P6Spy Options File #
  22. # See documentation for detailed instructions #
  23. # http://p6spy.github.io/p6spy/2.0/configandusage.html #
  24. #################################################################
  25. #################################################################
  26. # MODULES #
  27. # #
  28. # Module list adapts the modular functionality of P6Spy. #
  29. # Only modules listed are active. #
  30. # (default is com.p6spy.engine.logging.P6LogFactory and #
  31. # com.p6spy.engine.spy.P6SpyFactory) #
  32. # Please note that the core module (P6SpyFactory) can't be #
  33. # deactivated. #
  34. # Unlike the other properties, activation of the changes on #
  35. # this one requires reload. #
  36. #################################################################
  37. #modulelist=com.p6spy.engine.spy.P6SpyFactory,com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
  38. ################################################################
  39. # CORE (P6SPY) PROPERTIES #
  40. ################################################################
  41. # A comma separated list of JDBC drivers to load and register.
  42. # (default is empty)
  43. #
  44. # Note: This is normally only needed when using P6Spy in an
  45. # application server environment with a JNDI data source or when
  46. # using a JDBC driver that does not implement the JDBC 4.0 API
  47. # (specifically automatic registration).
  48. #driverlist=
  49. driverlist=com.mysql.jdbc.Driver
  50. # for flushing per statement
  51. # (default is false)
  52. #autoflush = false
  53. # sets the date format using Java's SimpleDateFormat routine.
  54. # In case property is not set, miliseconds since 1.1.1970 (unix time) is used (default is empty)
  55. #dateformat=
  56. # prints a stack trace for every statement logged
  57. #stacktrace=false
  58. # if stacktrace=true, specifies the stack trace to print
  59. #stacktraceclass=
  60. # determines if property file should be reloaded
  61. # Please note: reload means forgetting all the previously set
  62. # settings (even those set during runtime - via JMX)
  63. # and starting with the clean table
  64. # (default is false)
  65. #reloadproperties=false
  66. reloadproperties=true
  67. # determines how often should be reloaded in seconds
  68. # (default is 60)
  69. #reloadpropertiesinterval=60
  70. # specifies the appender to use for logging
  71. # Please note: reload means forgetting all the previously set
  72. # settings (even those set during runtime - via JMX)
  73. # and starting with the clean table
  74. # (only the properties read from the configuration file)
  75. # (default is com.p6spy.engine.spy.appender.FileLogger)
  76. #appender=com.p6spy.engine.spy.appender.Slf4JLogger
  77. #appender=com.p6spy.engine.spy.appender.StdoutLogger
  78. #appender=com.p6spy.engine.spy.appender.FileLogger
  79. appender=com.p6spy.engine.spy.appender.Slf4JLogger
  80. # name of logfile to use, note Windows users should make sure to use forward slashes in their pathname (e:/test/spy.log)
  81. # (used for com.p6spy.engine.spy.appender.FileLogger only)
  82. # (default is spy.log)
  83. #logfile = spy.log
  84. # append to the p6spy log file. if this is set to false the
  85. # log file is truncated every time. (file logger only)
  86. # (default is true)
  87. #append=true
  88. # class to use for formatting log messages (default is: com.p6spy.engine.spy.appender.SingleLineFormat)
  89. #logMessageFormat=com.p6spy.engine.spy.appender.SingleLineFormat
  90. logMessageFormat=com.dmsdbj.itoo.tool.p6spy.P6SpyLogger
  91. # format that is used for logging of the date/time/... (has to be compatible with java.text.SimpleDateFormat)
  92. # (default is dd-MMM-yy)
  93. #databaseDialectDateFormat=dd-MMM-yy
  94. databaseDialectDateFormat=yyyy-MM-dd hh:mm:ss
  95. # whether to expose options via JMX or not
  96. # (default is true)
  97. #jmx=true
  98. # if exposing options via jmx (see option: jmx), what should be the prefix used?
  99. # jmx naming pattern constructed is: com.p6spy(.<jmxPrefix>)?:name=<optionsClassName>
  100. # please note, if there is already such a name in use it would be unregistered first (the last registered wins)
  101. # (default is none)
  102. #jmxPrefix=
  103. #################################################################
  104. # DataSource replacement #
  105. # #
  106. # Replace the real DataSource class in your application server #
  107. # configuration with the name com.p6spy.engine.spy.P6DataSource #
  108. # (that provides also connection pooling and xa support). #
  109. # then add the JNDI name and class name of the real #
  110. # DataSource here #
  111. # #
  112. # Values set in this item cannot be reloaded using the #
  113. # reloadproperties variable. Once it is loaded, it remains #
  114. # in memory until the application is restarted. #
  115. # #
  116. #################################################################
  117. #realdatasource=/RealMySqlDS
  118. #realdatasourceclass=com.mysql.jdbc.jdbc2.optional.MysqlDataSource
  119. #################################################################
  120. # DataSource properties #
  121. # #
  122. # If you are using the DataSource support to intercept calls #
  123. # to a DataSource that requires properties for proper setup, #
  124. # define those properties here. Use name value pairs, separate #
  125. # the name and value with a semicolon, and separate the #
  126. # pairs with commas. #
  127. # #
  128. # The example shown here is for mysql #
  129. # #
  130. #################################################################
  131. #realdatasourceproperties=port;3306,serverName;myhost,databaseName;jbossdb,foo;bar
  132. #################################################################
  133. # JNDI DataSource lookup #
  134. # #
  135. # If you are using the DataSource support outside of an app #
  136. # server, you will probably need to define the JNDI Context #
  137. # environment. #
  138. # #
  139. # If the P6Spy code will be executing inside an app server then #
  140. # do not use these properties, and the DataSource lookup will #
  141. # use the naming context defined by the app server. #
  142. # #
  143. # The two standard elements of the naming environment are #
  144. # jndicontextfactory and jndicontextproviderurl. If you need #
  145. # additional elements, use the jndicontextcustom property. #
  146. # You can define multiple properties in jndicontextcustom, #
  147. # in name value pairs. Separate the name and value with a #
  148. # semicolon, and separate the pairs with commas. #
  149. # #
  150. # The example shown here is for a standalone program running on #
  151. # a machine that is also running JBoss, so the JDNI context #
  152. # is configured for JBoss (3.0.4). #
  153. # #
  154. # (by default all these are empty) #
  155. #################################################################
  156. #jndicontextfactory=org.jnp.interfaces.NamingContextFactory
  157. #jndicontextproviderurl=localhost:1099
  158. #jndicontextcustom=java.naming.factory.url.pkgs;org.jboss.nameing:org.jnp.interfaces
  159. #jndicontextfactory=com.ibm.websphere.naming.WsnInitialContextFactory
  160. #jndicontextproviderurl=iiop://localhost:900
  161. ################################################################
  162. # P6 LOGGING SPECIFIC PROPERTIES #
  163. ################################################################
  164. # filter what is logged
  165. # please note this is a precondition for usage of: include/exclude/sqlexpression
  166. # (default is false)
  167. #filter=false
  168. # comma separated list of strings to include
  169. # please note that special characters escaping (used in java) has to be done for the provided regular expression
  170. # (default is empty)
  171. #include =
  172. # comma separated list of strings to exclude
  173. # (default is empty)
  174. #exclude =
  175. # sql expression to evaluate if using regex
  176. # please note that special characters escaping (used in java) has to be done for the provided regular expression
  177. # (default is empty)
  178. #sqlexpression =
  179. #list of categories to exclude: error, info, batch, debug, statement,
  180. #commit, rollback and result are valid values
  181. # (default is info,debug,result,resultset,batch)
  182. #excludecategories=info,debug,result,resultset,batch
  183. excludecategories=info,debug,result,resultset
  184. # Execution threshold applies to the standard logging of P6Spy.
  185. # While the standard logging logs out every statement
  186. # regardless of its execution time, this feature puts a time
  187. # condition on that logging. Only statements that have taken
  188. # longer than the time specified (in milliseconds) will be
  189. # logged. This way it is possible to see only statements that
  190. # have exceeded some high water mark.
  191. # This time is reloadable.
  192. #
  193. # executionThreshold=integer time (milliseconds)
  194. # (default is 0)
  195. #executionThreshold=
  196. ################################################################
  197. # P6 OUTAGE SPECIFIC PROPERTIES #
  198. ################################################################
  199. # Outage Detection
  200. #
  201. # This feature detects long-running statements that may be indicative of
  202. # a database outage problem. If this feature is turned on, it will log any
  203. # statement that surpasses the configurable time boundary during its execution.
  204. # When this feature is enabled, no other statements are logged except the long
  205. # running statements. The interval property is the boundary time set in seconds.
  206. # For example, if this is set to 2, then any statement requiring at least 2
  207. # seconds will be logged. Note that the same statement will continue to be logged
  208. # for as long as it executes. So if the interval is set to 2, and the query takes
  209. # 11 seconds, it will be logged 5 times (at the 2, 4, 6, 8, 10 second intervals).
  210. #
  211. # outagedetection=true|false
  212. # outagedetectioninterval=integer time (seconds)
  213. #
  214. # (default is false)
  215. #outagedetection=false
  216. # (default is 60)
  217. #outagedetectioninterval=30

三、数据库datasource.xml:

  1. <!--数据库连接设置-->
  2. <bean id="dataSource" class="com.p6spy.engine.spy.P6DataSource">
  3. <constructor-arg>
  4. <ref bean="dataSourceDefault"/>
  5. </constructor-arg>
  6. </bean>

四、local下的log4j.properties文件添加代码(红框里的为新加代码):
这里写图片描述

五、初次运行效果:

  1. #####-----1504860808714|2|statement|connection 0|SELECT * FROM t_course c LEFT JOIN t_teacher_course tc ON tc.course_id =c.id LEFT JOIN t_training_programs tp ON tp.course_id=c.id WHERE tp.semester_id = ? AND tp.grade = ? AND tc.teacher_id = ? AND c.is_delete = 0 AND tc.is_delete = 0 AND tp.is_delete = 0|SELECT * FROM t_course c LEFT JOIN t_teacher_course tc ON tc.course_id =c.id LEFT JOIN t_training_programs tp ON tp.course_id=c.id WHERE tp.semester_id = 'YVMEMS37M5KWYDM7LXEX01' AND tp.grade = '2013级' AND tc.teacher_id = '06493cbbdf79f909d6ab0a' AND c.is_delete = 0 AND tc.is_delete = 0 AND tp.is_delete = 0

但是这样的结果,我们还是不太清晰,P6SpyLogger打印的不该是这样的格式,后来发现是tool里的jar包没有下载,于是:

1、在资源管理器中打开代码,按shift+鼠标右键,打开命令窗口:
这里写图片描述
2、命令窗口中输入:mvn compile -U,强制下载tool里jar包:
这里写图片描述

六、最终运行结果:

  1. #####-----2017-09-08 16:59:16:358 | took 3ms | statement | connection 0
  2. SELECT * FROM t_course c LEFT JOIN t_teacher_course tc ON tc.course_id =c.id LEFT JOIN t_training_programs tp ON tp.course_id=c.id WHERE tp.semester_id = 'YVMEMS37M5KWYDM7LXEX01' AND tp.grade = '2013级' AND tc.teacher_id = '06493cbbdf79f909d6ab0a' AND c.is_delete = 0 AND tc.is_delete = 0 AND tp.is_delete = 0;

这样我们就可以直观看出sql语句,直接到navicat测试了,怎么样,这样是不是很方便,快来试试吧!

感谢您的阅读!

发表评论

表情:
评论列表 (有 0 条评论,529人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Mybatis 配置p6spy

    在开发中,为了更方便的知道编写的sql语句是否正确,则通过配置p6spy在控制台打印sql语句,从而解决因sql语句错误导致的程序运行失败,配置方式如下: 1,导入p6sp

    相关 使用P6Spy格式化SQL语句

    公司最近在做一个项目,开发过程中遇到点小问题,查询结果出不来,查看自带日志打印,有点不爽,特别是想复制sql语句到数据库navicat中去调试时,还要手动复制参数值,很是麻烦,

    相关 P6Spy

     P6Spy是一个可以用来在应用程序中拦截和修改数据操作语句的开源框架。通过P6Spy我们可以对SQL语句进行拦截,相当于一个SQL语句的记录器,这样我们可以用它来作相关的分析