欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MyBatis集成P6Spy显示实际的SQL(代码教程)

程序员文章站 2022-03-31 09:28:36
在应用程序开发过程中,为了方便调试,通常都需要知道在DAO层,程序执行的SQL是什么,而P6spy这个组件正是提供了该功能。 接下来将详细介绍P6Spy的详细使用。 一 系统集...

在应用程序开发过程中,为了方便调试,通常都需要知道在DAO层,程序执行的SQL是什么,而P6spy这个组件正是提供了该功能。

接下来将详细介绍P6Spy的详细使用。

系统集成P6spy

1 添加依赖

3.6.01.1.6p6spyp6spy${p6spy.version}com.alibabadruid${druid.version}

2 实现自定义的SQL输出格式
为了输出的内容足够的简洁,这里只保留了当期那时间,执行SQL的耗时以及执行的SQL语句

package net.ittimeline.mybatis.practices.core;

import com.alibaba.druid.sql.SQLUtils;
import com.p6spy.engine.spy.appender.MessageFormattingStrategy;

/**
 * @author tony ittimeline@163.com
 * @date 2018-01-30-下午10:45
 * @website wwww.ittimeline.net
 * @see
 * @since JDK8u162
 */
public class CustomizeLineFormat implements MessageFormattingStrategy {

    public String buildMessage(String now, long elapsed, String sql) {
        StringBuffer content = new StringBuffer();
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(now) && org.apache.commons.lang3.StringUtils.isNotEmpty(Long.valueOf(elapsed).toString())
                && org.apache.commons.lang3.StringUtils.isNotEmpty(sql)) {
            content.append("当前时间:" + now);
            content.append(" SQL执行耗时(毫秒)为" + elapsed);
            content.append(" SQL执行的语句是\n" + SQLUtils.formatMySql(sql)+"\n\n");
        }
        return content.toString();
    }

    @Override
    public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql) {
        return buildMessage(now, elapsed, sql);
    }

}

3 配置spy.properties

该文件只需要配置
modulelist,logfile,logMessageFormat,dateformat即可。

###
# #%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
#
#      https://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                   #
# https://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
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=
#url="jdbc:p6spy:oracle:thin:@localhost:1521:orcl" \u5176\u4e2d\u7684p6spy\u5fc5\u987b\u8981\uff0c\u56e0\u4e3a\u8fd9\u6837\u624d\u4f1a\u88ab\u62e6\u622a
#drive=com.p6spy.engine.spy.P6SpyDriver
driverlist=com.mysql.jdbc.Driver
# for flushing per statement
# (default is false)
#autoflush = false


# 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

# 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

# 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
#windows \u7528\u6237\u8bf7\u7528 C:/spy.log \u683c\u5f0f\uff0c\u4e0d\u8981\u7528\
logfile=mybatis-practices-core.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)
\uff03\u8ffd\u52a0\u5230 p6spy \u65e5\u5fd7\u6587\u4ef6\u3002\u5982\u679c\u8bbe\u7f6e\u4e3afalse
\uff03\u65e5\u5fd7\u6587\u4ef6\u88ab\u622a\u65ad\u6bcf\u6b21\u3002 \uff08\u53ea\u9650\u4e8e\u6587\u4ef6\u8bb0\u5f55\u5668\uff09
\uff03\uff08\u9ed8\u8ba4\u4e3atrue\uff09
#append=true

# class to use for formatting log messages (default is: com.p6spy.engine.spy.appender.SingleLineFormat)
#\u591a\u884c\u8f93\u51fa\u4e3a com.p6spy.engine.spy.appender.MultiLineFormat
#\u884c\u7684\u65f6\u95f4\u683c\u5f0f\u5316\u914d\u7f6e\u5728 dateformat \u8bbe\u5b9a
#current time|execution time|category|connection id|statement SQL String|effective SQL string
#\u65e5\u5fd7\u683c\u5f0f\u4e3a \u5f53\u524d\u65f6\u95f4\u6233|\u6267\u884c\u8bed\u53e5\u82b1\u8d39\u7684\u65f6\u95f4|\u8c03\u7528\u7684\u7c7b\u522b|connectionId|\u58f0\u660eSQL\u5b57\u7b26\u4e32|\u6709\u6548\u7684SQL\u5b57\u7b26\u4e32
#logMessageFormat=com.p6spy.engine.spy.appender.SingleLineFormat
logMessageFormat= net.ittimeline.mybatis.practices.core.CustomizeLineFormat

# format that is used for logging of the date/time/... (has to be compatible with java.text.SimpleDateFormat)
# (default is dd-MMM-yy)
databaseDialectDateFormat=yyyy-MM-dd HH:mm:ss

# 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=
dateformat=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(.)?:name=
# 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

# 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

二 MyBatis集成P6spy

MyBatis集成P6spy,这里倒不如说成DataSource集成P6Spy更贴切,
这里增加一个名为database.properties的文件,内容如下

jdbc.driver=com.p6spy.engine.spy.P6SpyDriver
jdbc.url=jdbc:p6spy:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&useSSL=false
jdbc.username=root
jdbc.password=guanglei

主要包含了数据库的连接信息,和之前的配置不同的是更换了驱动实现以及数据库连接地址。而mybatis-config.xml文件中只需要增加一行配置,然后就可以采用${属性名}的方式获取数据库配置了,配置如下所示



然后运行ContryMapperTest.selectAll()方法,会发现在模块的根路径下存在一个mybatis-practices-core.log的文件,内容如下

当前时间:2018-01-30 23:03:07 SQL执行耗时(毫秒)为0 SQL执行的语句是
SELECT country_id AS countryId, country_name AS countryName, country_code AS countryCode
FROM t_country