經過第三方日誌工具能夠控制日誌級別的輸出,可是咱們發現mybatis輸出的SQL不是那麼的完整,咱們SQL裏的參數值並無打印出來,下面我就來說講怎麼樣對mybatis的輸出sql格式化。java
首先我這個案例是基於Spring boot 來開發的,因此配置和傳統的xml配置有所區別,spring boot大大簡化了一些配置,它把配置放到java代碼,咱們只須要使用註解就可替代一些之前xml的配置。spring
自定義攔截器sql
import java.io.PrintStream; import java.text.DateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.regex.Matcher; import org.apache.commons.collections.CollectionUtils; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.ParameterMapping; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.plugin.Intercepts; import org.apache.ibatis.plugin.Invocation; import org.apache.ibatis.plugin.Plugin; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.type.TypeHandlerRegistry; import org.springframework.stereotype.Component; /** * 自定義mybatis攔截器,格式化SQL輸出, * * @author zengsong * @version 1.0 * @description 只對查詢和更新語句作了格式化,其它語句須要手動添加 * @date 2019/5/30 10:17 **/ @Intercepts({@org.apache.ibatis.plugin.Signature(type=org.apache.ibatis.executor.Executor.class, method="update", args={MappedStatement.class, Object.class}),
@org.apache.ibatis.plugin.Signature(type=org.apache.ibatis.executor.Executor.class, method="query", args={MappedStatement.class, Object.class, org.apache.ibatis.session.RowBounds.class, org.apache.ibatis.session.ResultHandler.class})}) @Component public class MybatisResultInterceptor implements Interceptor { public Object intercept(Invocation invocation) throws Throwable { try { MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0]; Object parameter = null; if (invocation.getArgs().length > 1) { parameter = invocation.getArgs()[1]; } String sqlId = mappedStatement.getId(); BoundSql boundSql = mappedStatement.getBoundSql(parameter); Configuration configuration = mappedStatement.getConfiguration(); String sql = getSql(configuration, boundSql, sqlId); System.out.println(sql); } catch (Exception localException) {} return invocation.proceed(); } public static String getSql(Configuration configuration, BoundSql boundSql, String sqlId) { String sql = showSql(configuration, boundSql); StringBuilder str = new StringBuilder(100); str.append(sqlId); str.append(":"); str.append(sql); return str.toString(); } private static String getParameterValue(Object obj) { String value = null; if ((obj instanceof String)) { value = "'" + obj.toString() + "'"; } else if ((obj instanceof Date)) { DateFormat formatter = DateFormat.getDateTimeInstance(2, 2, Locale.CHINA); value = "'" + formatter.format(new Date()) + "'"; } else if (obj != null) { value = obj.toString(); } else { value = ""; } return value; } public static String showSql(Configuration configuration, BoundSql boundSql) { Object parameterObject = boundSql.getParameterObject(); List<ParameterMapping> parameterMappings = boundSql.getParameterMappings(); String sql = boundSql.getSql().replaceAll("[\\s]+", " "); MetaObject metaObject; if ((CollectionUtils.isNotEmpty(parameterMappings)) && (parameterObject != null)) { TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry(); if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) { sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(parameterObject))); } else { metaObject = configuration.newMetaObject(parameterObject); for (ParameterMapping parameterMapping : parameterMappings) { String propertyName = parameterMapping.getProperty(); if (metaObject.hasGetter(propertyName)) { Object obj = metaObject.getValue(propertyName); sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj))); } else if (boundSql.hasAdditionalParameter(propertyName)) { Object obj = boundSql.getAdditionalParameter(propertyName); sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj))); } else { sql = sql.replaceFirst("\\?", "缺失"); } } } } return sql; } public Object plugin(Object target) { return Plugin.wrap(target, this); } public void setProperties(Properties properties) {} }
配置攔截器apache
import com.sengled.cloud.data.platform.dao.mybatis.MybatisResultInterceptor; import java.util.Properties; import javax.annotation.Resource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * 自定義mybatis攔截器 * * @author zengsong * @version 1.0 * @description * @date 2019/5/30 10:17 **/ @Configuration public class MybatisInterceptorConfig { @Resource private MybatisResultInterceptor mybatisResultInterceptor; @Bean public String myInterceptor() { Properties properties = new Properties(); this.mybatisResultInterceptor.setProperties(properties); return "interceptor"; } }
配置日誌級別session
<logger name="com.apache.ibatis" level="TRACE"/> <logger name="java.sql.Connection" level="DEBUG"/> <logger name="java.sql.Statement" level="DEBUG"/> <logger name="java.sql.PreparedStatement" level="DEBUG"/> <root level="INFO"> <appender-ref ref="STDOUT" /> <appender-ref ref="FILE" /> </root>