Mybatis日志打印美化sql语句

image.png

原本的Mybatis log会分两行打印日志,参数用占位,实际参数在另一行,对于阅读体验很不好,现在可以使用填充替换后的sql语句。

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;

@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class,
                ResultHandler.class, CacheKey.class, BoundSql.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class,
                ResultHandler.class}),
        @Signature(type = Executor.class, method = "commit", args = {boolean.class})})
@Slf4j(topic = "sql")
public class MybatisLogInterceptor implements Interceptor {

    private static final int SLOW_QUERY_TIME = 1000;

    private DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);

    private Logger slowQueryLogger = LoggerFactory.getLogger("sqlSlowQuery");


    public Object intercept(Invocation invocation) throws Throwable {
        if (invocation.getMethod().getName().equals("commit")) {

            long start = System.nanoTime();
            Object returnValue = invocation.proceed();
            long end = System.nanoTime();

            log.info("Sql commit time: " + (end - start) / 1000000);

            return returnValue;
        } else {
            MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
            Object parameter = null;
            if (invocation.getArgs().length > 1) {
                parameter = invocation.getArgs()[1];
            }

            BoundSql boundSql = null;
            // 适配通过PageHelper分页之后,原sql已经被修改,通过参数才能拿到修改后的sql
            if (invocation.getArgs().length == 6) {
                Object arg_5 = invocation.getArgs()[5];
                if (arg_5 instanceof BoundSql) {
                    boundSql = (BoundSql) arg_5;
                }
            }

            if (null == boundSql) {
                boundSql = mappedStatement.getBoundSql(parameter);
            }

            Configuration configuration = mappedStatement.getConfiguration();
            String sql = this.generateSql(configuration, boundSql);
            String sqlId = mappedStatement.getId();

            long start = System.nanoTime();

            Object returnValue = null;
            try {
                returnValue = invocation.proceed();
            } catch (Exception e) {
                log.info(sqlId + ":  " + sql);
                throw e;
            }
            long end = System.nanoTime();

            long executeTime = (end - start) / 1000000;

            log.info(sqlId + ":  " + sql + "  time: " + executeTime);

            if (mappedStatement.getSqlCommandType() == SqlCommandType.SELECT && executeTime > SLOW_QUERY_TIME) {
                slowQueryLogger.info(sqlId + ":  " + sql + "  time: " + executeTime);
            }

            return returnValue;
        }
    }

    private String generateSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        if (parameterMappings.size() > 0 && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));
            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    Object obj = null;
                    if (metaObject.hasGetter(propertyName)) {
                        obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj).replace("$", "\\$"));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj).replace("$", "\\$"));
                    }
                    sql = this.addAddtionalInfo(sql, obj, propertyName);
                }
            }
        }
        return sql;
    }

    protected String addAddtionalInfo(String sql, Object obj, String propertyName) {
        return sql;
    }

    private String getParameterValue(Object obj) {

        String value;
        if (null == obj) {
            value = StringUtils.EMPTY;
        } else if (obj instanceof Date) {
            value = "'" + formatter.format((Date) obj) + "'";
        } else if (ClassUtils.isAssignable(obj.getClass(), Number.class)) { // 数字类型不添加引号包裹
            value = obj.toString();
        } else {
            value = "'" + obj.toString() + "'";
        }
        return value;
    }

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

    @Override
    public void setProperties(Properties properties) {
    }
}
# 数据库 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×