MyBatis自定义拦截器实现优化SQL日志输出

 更新时间:2026年03月16日 08:43:41   作者:汤姆yu  
这篇文章主要介绍了优化MyBatisPlus SQL日志输出的方案,针对默认日志格式存在的不足,例如缺少时间、可读性差、存储成本高等,希望对大家有所帮助

1、背景

MyBatis Plus 通过配置文件中设置 log-impl 属性来指定日志实现,以打印 SQL 语句。

mybatis-plus:
  configuration:
    log-impl:org.apache.ibatis.logging.stdout.StdOutImpl
logging:
  level:
    org.ylzl.eden.demo.mapper:DEBUG

打印出来的 SQL 内容如下:

==>  Preparing: SELECT id,login,email,activated,locked,lang_key,activation_key,reset_key,reset_date,created_by,created_date,last_modified_by,last_modified_date FROM demo_user WHERE id=?
==> Parameters: 1(Long)
<==  Columns: ID, LOGIN, EMAIL, ACTIVATED, LOCKED, LANG_KEY, ACTIVATION_KEY, RESET_KEY, RESET_DATE, CREATED_BY, CREATED_DATE, LAST_MODIFIED_BY, LAST_MODIFIED_DATE
<==  Row: 1, admin, 1813986321@qq.com, TRUE, FALSE, zh-cn, null, null, null, system, 2025-02-10 22:31:03.818, system, null
<==  Total: 1

然而,默认的日志输出格式存在以下不足:

  • 缺少日志时间,无法快速定位 SQL 执行时间。
  • SQL 语句可读性差,复杂的 SQL 语句难以阅读。
  • 日志存储成本高:SQL 模板占用较多字符,增加了日志存储成本。

2、目标

通过 MyBatis 的拦截器实现 SQL 原始语句的打印。

3、实现

首先,自定义 MyBatis 拦截器,实现 org.apache.ibatis.plugin.Interceptor 接口。

@Intercepts({
@Signature(method = "query", type = Executor.class, args= {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
 @Signature(method= "query", type = Executor.class, args= {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
 @Signature(method= "update", type = Executor.class, args= {MappedStatement.class, Object.class})
})
publicclassMybatisSqlLogInterceptorimplementsInterceptor{
privatestaticfinal Logger log = LoggerFactory.getLogger("MybatisSqlLog");
private Duration slownessThreshold = Duration.ofMillis(1000);
@Override
public Object intercept(Invocation invocation)throws Throwable {
  MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
  String mapperId = mappedStatement.getId();
  String originalSql = MybatisUtils.getSql(mappedStatement, invocation);
long start = SystemClock.now();
  Object result = invocation.proceed();
long duration = SystemClock.now() - start;
        // 当 SQL 执行超过我们设置的阈值,转为 WARN 级别 
if (Duration.ofMillis(duration).compareTo(slownessThreshold) < 0) {
   log.info("{} execute sql: {} ({} ms)", mapperId, originalSql, duration);
  } else {
   log.warn("{} execute sql took more than {} ms: {} ({} ms)", mapperId, slownessThreshold.toMillis(), originalSql, duration);
  }
return result;
 }
@Override
public Object plugin(Object target){
if (target instanceof Executor) {
   return Plugin.wrap(target, this);
  }
return target;
 }
    // 设置慢 SQL 阈值,单位为秒
publicvoidsetSlownessThreshold(Duration slownessThreshold){
this.slownessThreshold = slownessThreshold;
 }
}

笔者编写了一个工具类负责解析 MyBatis 执行语句,还原为可执行的 SQL 内容。

@UtilityClass
publicclassMybatisUtils{

    privatestaticfinal Pattern PARAMETER_PATTERN = Pattern.compile("\\?");

public String getSql(MappedStatement mappedStatement, Invocation invocation){
  Object parameter = null;
if (invocation.getArgs().length > 1) {
   parameter = invocation.getArgs()[1];
  }
  BoundSql boundSql = mappedStatement.getBoundSql(parameter);
  Configuration configuration = mappedStatement.getConfiguration();
return resolveSql(configuration, boundSql);
 }

privatestatic String resolveSql(Configuration configuration, BoundSql boundSql){
  Object parameterObject = boundSql.getParameterObject();
  List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
  String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
if (!parameterMappings.isEmpty() && parameterObject != null) {
   TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
   if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
    sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(resolveParameterValue(parameterObject)));

   } else {
    MetaObject metaObject = configuration.newMetaObject(parameterObject);
    Matcher matcher = PARAMETER_PATTERN.matcher(sql);
    StringBuffer sqlBuffer = new StringBuffer();
    for (ParameterMapping parameterMapping : parameterMappings) {
     String propertyName = parameterMapping.getProperty();
     Object obj = null;
     if (metaObject.hasGetter(propertyName)) {
      obj = metaObject.getValue(propertyName);
     } elseif (boundSql.hasAdditionalParameter(propertyName)) {
      obj = boundSql.getAdditionalParameter(propertyName);
     }
     if (matcher.find()) {
      matcher.appendReplacement(sqlBuffer, Matcher.quoteReplacement(resolveParameterValue(obj)));
     }
    }
    matcher.appendTail(sqlBuffer);
    sql = sqlBuffer.toString();
   }
  }
return sql;
 }

privatestatic String resolveParameterValue(Object obj){
if (obj instanceof CharSequence) {
   return"'" + obj + "'";
  }
if (obj instanceof Date) {
   DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
   return"'" + formatter.format(obj) + "'";
  }
return obj == null ? "" : String.valueOf(obj);
 }
}

将 MyBatis 拦截器设置为 Spring 自动装配。

@AutoConfigureAfter(DataSourceAutoConfiguration.class)
@ConditionalOnBean(SqlSessionFactory.class)
@ConditionalOnProperty(name= "mybatis.plugin.sql-log.enabled")
@EnableConfigurationProperties({MybatisPluginProperties.class})
@RequiredArgsConstructor
@Slf4j
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@Configuration(proxyBeanMethods= false)
publicclassMybatisPluginAutoConfiguration{

privatefinal MybatisPluginProperties mybatisPluginProperties;

@Bean
public MybatisSqlLogInterceptor mybatisSqlLogInterceptor(){
  MybatisSqlLogInterceptor interceptor = new MybatisSqlLogInterceptor();
  interceptor.setSlownessThreshold(mybatisPluginProperties.getSqlLog().getSlownessThreshold());
return interceptor;
 }
}

@Data
@ConfigurationProperties(prefix = "mybatis.plugin")
publicclassMybatisPluginProperties{

privatefinal SqlLog sqlLog = new SqlLog();

@Data
publicstaticclassSqlLog{

privateboolean enabled = true;

private Duration slownessThreshold = Duration.ofMillis(1000);
 }
}

当项目配置了属性 mybatis.plugin.sql-log.enabled=true 时,SQL 拦截将生效,打印的内容如下:

2024-02-10 23:03:01.845 INFO  [dev] [XNIO-1 task-1] org.ylzl.eden.demo.infrastructure.user.database.UserMapper.selectById execute sql: SELECT id,login,email,activated,locked,lang_key,activation_key,reset_key,reset_date,created_by,created_date,last_modified_by,last_modified_date FROM demo_user WHERE id=1 (10 ms)

这种日志格式比较符合我们实际的生产要求:提供日志时间、可运行的 SQL、执行耗时。

4、产出

团队引入这个组件后,在定位生产 SQL 问题时,比原来清晰多了,并且,日志文件缩减了 30% 存储成本。

到此这篇关于MyBatis自定义拦截器实现优化SQL日志输出的文章就介绍到这了,更多相关MyBatis自定义拦截器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java实现5种限流算法及7种限流方式

    Java实现5种限流算法及7种限流方式

    本文主要介绍了Java实现5种限流算法及7种限流方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-08-08
  • 基于多线程并发的常见问题(详解)

    基于多线程并发的常见问题(详解)

    下面小编就为大家带来一篇基于多线程并发的常见问题(详解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • plantuml画图实现代码画时序图UML用例图

    plantuml画图实现代码画时序图UML用例图

    这篇文章主要为大家介绍了plantuml画图实现代码画时序图示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-07-07
  • Spring接口版本控制方案及RequestMappingHandlerMapping接口介绍(最新推荐)

    Spring接口版本控制方案及RequestMappingHandlerMapping接口介绍(最新推荐)

    RequestMappingHandlerMapping接口是Spring MVC中的一个核心组件,负责处理请求映射和处理器的匹配这篇文章主要介绍了Spring接口版本控制方案及RequestMappingHandlerMapping接口介绍,需要的朋友可以参考下
    2024-07-07
  • Spring Boot全局异常处理与日志监控全解析

    Spring Boot全局异常处理与日志监控全解析

    本文给大家介绍Spring Boot全局异常处理与日志监控全解析,通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2025-08-08
  • MyBatis中的配置文件详解

    MyBatis中的配置文件详解

    在 MyBatis 中,配置文件分为 全局配置文件(核心配置文件)和映射配置文件,本文给大家介绍MyBatis中的配置文件相关知识,感兴趣的朋友一起看看吧
    2023-10-10
  • 使用Spring自身提供的地址匹配工具匹配URL操作

    使用Spring自身提供的地址匹配工具匹配URL操作

    这篇文章主要介绍了使用Spring自身提供的地址匹配工具匹配URL操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-09-09
  • java中TestNG使用教程详解

    java中TestNG使用教程详解

    TestNG是Java中的一个测试框架, 类似于JUnit 和NUnit, 本文主要介绍了java中TestNG使用教程详解,具有一定的参考价值,感兴趣的可以了解一下
    2021-12-12
  • 关于@PropertySource配置的用法解析

    关于@PropertySource配置的用法解析

    这篇文章主要介绍了关于@PropertySource配置的用法解析,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-03-03
  • java集合框架 arrayblockingqueue应用分析

    java集合框架 arrayblockingqueue应用分析

    ArrayBlockingQueue是一个由数组支持的有界阻塞队列。此队列按 FIFO(先进先出)原则对元素进行排序。队列的头部 是在队列中存在时间最长的元素
    2012-11-11

最新评论