SpringBoot项目实现日志打印SQL明细(包括SQL语句和参数)几种方式

前言

我们在开发项目的时候,都会连接数据库。有时候遇到问题需要根据我们编写的SQL进行分析,但如果不进行一些开发或者配置的话,这些SQL是不会打印到控制台的,它们默认是隐藏的。下面给大家介绍几种常用的方法。

第一种、代码形式

Mybatis框架是Java程序员最常用的数据库映射框架,MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis 允许使用插件来拦截的方法调用。那么我们可以根据这个机制来获取我们执行的sql语句以及参数。下面的SqlExecuteTimeCountInterceptor.java直接复制到SpringBoot项目就可以使用了。

1. 代码如下

package com.example.springbootsqlmonitor.config;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.sql.Statement;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;


@Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),
        @Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),
        @Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})})
@Component
public class SqlExecuteTimeCountInterceptor implements Interceptor {

    private static final Logger logger = LoggerFactory.getLogger(SqlExecuteTimeCountInterceptor.class);

    /**
     * 打印的参数字符串的最大长度
     */
    private final static int MAX_PARAM_LENGTH = 50;

    /**
     * 记录的最大SQL长度
     */
    private final static int MAX_SQL_LENGTH = 500;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object target = invocation.getTarget();
        long startTime = System.currentTimeMillis();
        StatementHandler statementHandler = (StatementHandler) target;
        try {
            return invocation.proceed();
        } finally {
            long endTime = System.currentTimeMillis();
            long timeCount = endTime - startTime;

            BoundSql boundSql = statementHandler.getBoundSql();
            String sql = boundSql.getSql();
            Object parameterObject = boundSql.getParameterObject();
            List<ParameterMapping> parameterMappingList = boundSql.getParameterMappings();

            // 格式化Sql语句,去除换行符,替换参数
            sql = formatSQL(sql, parameterObject, parameterMappingList);

            logger.info("执行 SQL:[{}]执行耗时[ {} ms])", sql, timeCount);
        }
    }

    /**
     * 格式化/美化 SQL语句
     *
     * @param sql                  sql 语句
     * @param parameterObject      参数的Map
     * @param parameterMappingList 参数的List
     * @return 格式化之后的SQL
     */
    private String formatSQL(String sql, Object parameterObject, List<ParameterMapping> parameterMappingList) {
        // 输入sql字符串空判断
        if (sql == null || sql.length() == 0) {
            return "";
        }
        // 美化sql
        sql = beautifySql(sql);
        // 不传参数的场景,直接把sql美化一下返回出去
        if (parameterObject == null || parameterMappingList == null || parameterMappingList.size() == 0) {
            return sql;
        }
        return limitSQLLength(sql, parameterObject, parameterMappingList);
    }

    /**
     * 返回限制长度之后的SQL语句
     *
     * @param sql                  原始SQL语句
     * @param parameterObject
     * @param parameterMappingList
     */
    private String limitSQLLength(String sql, Object parameterObject, List<ParameterMapping> parameterMappingList) {
        if (sql == null || sql.length() == 0) {
            return "";
        }
        Map<String, Object> parameterMap = (Map<String, Object>) parameterObject;
        StringBuilder paramsBuilder = new StringBuilder("\n参数列表:");
        parameterMap.forEach((key, value) -> {
            parameterMappingList.forEach(parameterMapping -> {
                if (parameterMapping.getProperty().equals(key)) {
                    String detail = "[" + key + ":" + value + "];";
                    paramsBuilder.append(detail);
                }
            });
        });
        sql += paramsBuilder.toString();
        if (sql.length() > MAX_SQL_LENGTH) {
            return sql.substring(0, MAX_SQL_LENGTH);
        } else {
            return sql;
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

    /**
     * 美化sql
     *
     * @param sql sql语句
     */
    private String beautifySql(String sql) {
        sql = sql.replaceAll("[\\s\n ]+", "  ");
        return sql;
    }
}

2. 效果如下

2022-07-21 19:14:07.685  INFO 25936 --- [           main] c.e.s.c.SqlExecuteTimeCountInterceptor   : 执行 SQL:[SELECT  t3.user_id,  t3.user_name,  t2.role_id,  t2.role_name  FROM  my_user_role_rel  t1  LEFT  JOIN  my_role  t2  ON  t1.role_id  =  t2.role_id  LEFT  JOIN  my_user  t3  ON  t1.user_id  =  t3.user_id  WHERE  t1.user_id  =  ?  AND  t2.role_id  =  ?
参数列表:[roleId:1][userId:1]]执行耗时[ 18 ms])

第二种、Mybatis-Plus配置

如果你的项目用的是Mybatis-Plus框架,那么你可以不用写代码,直接用一行配置就可以实现sql日志监控:
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

1. 配置如下

# mybatis
mybatis.configuration.auto-mapping-behavior=full
mybatis.configuration.map-underscore-to-camel-case=true
mybatis-plus.mapper-locations=classpath*:/mybatis/mapper/*.xml
# 开启mybatis-plus自带SQL打印
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

2. 效果如下

Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@b14b60a] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1142d377] will not be managed by Spring
==>  Preparing: SELECT t3.user_id, t3.user_name, t2.role_id, t2.role_name FROM my_user_role_rel t1 LEFT JOIN my_role t2 ON t1.role_id = t2.role_id LEFT JOIN my_user t3 ON t1.user_id = t3.user_id WHERE t1.user_id = ? 
==> Parameters: 1(Long)
<==    Columns: user_id, user_name, role_id, role_name
<==        Row: 1, 用户1, 1, 超级管理员
<==        Row: 1, 用户1, 2, 游客
<==      Total: 2
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@b14b60a]

第三种、整合p6spy框架

使用p6spy这种形式是最复杂的,不过也是最好的,是专门用来跟踪数据库操作的。

1. maven引入


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

2. application.properties配置文件

这里要注意该两个地方:

spring.datasource.url=jdbc:p6spy:mysql://localhost:3306/mybatis-test?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true

spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver

spring.datasource.url=jdbc:p6spy:mysql://localhost:3306/mybatis-test?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=***
spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver

3. 在resources下创建spy.properties文件

内容如下:

# 开启模块sql记录和长时sql记录
module.log=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自己编写格式类
logMessageFormat=com.example.springbootsqlmonitor.config.P6spySqlFormatConfig

# 通过配置进行格式设置
#logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat
# 自定义sql输出格式
#customLogMessageFormat=%(currentTime) | TIME\uFF1A %(executionTime) ms | SQL\uFF1A %(sql)

# 日志输出方式(输出到控制台)
appender=com.p6spy.engine.spy.appender.StdoutLogger
#appender=com.p6spy.engine.spy.appender.Slf4JLogger

excludecategories=info,debug,result,resultset
deregisterdrivers=true
dateformat=yyyy-MM-dd HH:mm:ss
driverlist=com.mysql.cj.jdbc.Driver
# 开启长时sql记录
outagedetection=true
# 触发长时记录时限
outagedetectioninterval=2

4. 效果如下

耗时 5 ms | SQL 语句:
SELECT t3.user_id, t3.user_name, t2.role_id, t2.role_name FROM my_user_role_rel t1 LEFT JOIN my_role t2 ON t1.role_id = t2.role_id LEFT JOIN my_user t3 ON t1.user_id = t3.user_id WHERE t1.user_id = 1 AND t2.role_id = 1;

整合p6spy遇到的一些问题

1. 启动报错

Caused by: java.lang.IllegalStateException: dbType not support : null, url jdbc:p6spy:mysql://localhost:3306/mybatis-test?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true&zeroDateTimeBehavior=convertToNull

出现这个问题的原因是配置了Druid连接池,是它的一个属性导致的,把这个属性注释掉
spring.datasource.druid.filters=stat,wall

或者增加如下配置:
spring.datasource.druid.filter.wall.enabled=true spring.datasource.druid.filter.wall.db-type=mysql spring.datasource.druid.filter.stat.db-type=mysql spring.datasource.druid.filter.stat.enabled=true

2、spy.properties配置文件不生效

出现这个问题,一般要去检查一下你的jar包,看一下spy.properties文件有没有被打包进去。因为这个是不需要增加配置类的,是通过劫持数据库连接实现的

结语

对比上面这三种方式,其中p6spy打印的sql最完整,是可以直接放在数据库工具上执行的,而不是像Mybatis打印那种参数带问号的。但其实打印这些sql语句挺消耗性能的,建议到了线上把它给关掉,避免非业务消耗资源。

你可能感兴趣的:(后端篇-何必重复造轮子,数据库,spring,boot,sql)