springboot mybatisplus 打印慢sql
时间: 2025-05-14 09:32:40 浏览: 19
### 配置 Spring Boot 和 MyBatis Plus 打印慢查询 SQL
为了实现这一目标,在 `application.properties` 或者 `application.yml` 文件中可以设置特定属性来控制日志记录行为。
对于基于 `properties` 的配置文件:
```properties
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
logging.level.com.baomidou.mybatisplus.extension.spring.MybatisPlusAutoConfiguration=DEBUG
```
上述配置启用了 MyBatis Plus 日志功能并将其级别设为 DEBUG,这有助于捕获详细的执行信息[^1]。
然而,仅通过调整日志等级可能无法精确区分哪些是耗时过长的操作。为此,可以通过自定义拦截器的方式进一步增强监控能力。创建一个新的类继承 `AbstractBaseInterceptor` 并重写相应的方法以测量每次数据库交互所花费的时间。一旦检测到超过预设阈值的情况,则将该条目标记为“慢查询”。
下面是一个简单的 Java 实现例子:
```java
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import java.sql.Statement;
import java.util.Properties;
@Intercepts({
@Signature(type = StatementHandler.class, method = "query", args = {Statement.class})
})
public class SlowQueryLogger extends AbstractBaseInterceptor {
private static final int SLOW_QUERY_THRESHOLD_MS = 50; // 设置慢查询阈值为50毫秒
public Object intercept(Invocation invocation) throws Throwable {
long startTime = System.currentTimeMillis();
try {
return invocation.proceed();
} finally {
long endTime = System.currentTimeMillis();
if ((endTime - startTime) > SLOW_QUERY_THRESHOLD_MS) {
PluginUtils.getMetaObject(invocation.getTarget()).getValue("delegate.boundSql").toString());
System.out.println("Slow Query Detected: Took " + (endTime - startTime) + " ms");
}
}
}
public void setProperties(Properties properties) {}
}
```
这段代码展示了如何构建一个名为 `SlowQueryLogger` 的拦截器,用于监测所有查询操作,并当它们的执行时间超过了指定的阈值(这里是50ms)时发出警告。
最后一步是在应用程序启动期间注册这个新的拦截器实例。可以在主应用类上添加如下注解完成此过程:
```java
@Configuration
public class MyBatisConfig {
@Bean
public Interceptor slowQueryLogger() {
return new SlowQueryLogger();
}
}
```
这样就完成了整个流程——从基础的日志配置直到高级别的性能分析工具集成,使得开发者能够有效地追踪那些影响系统响应速度的关键因素。
阅读全文
相关推荐















