mybatis 打印查询日志

mybatis 打印慢查询日志

1. 配置日志框架

MyBatis 本身支持多种日志框架,如 Log4j、Log4j2、SLF4J 等。这里以 SLF4J 和 Logback 为例进行配置。

将 com.yourcompany.yourproject.dao 替换为你实际的 DAO 接口所在的包名。

2. 自定义拦截器

通过自定义拦截器来记录慢查询日志。以下是一个示例代码:

java
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Statement;
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})
})
public class SlowQueryInterceptor implements Interceptor {
    private static final Logger logger = LoggerFactory.getLogger(SlowQueryInterceptor.class);
    // 慢查询时间阈值,单位:毫秒
    private long slowQueryThreshold = 1000;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        long startTime = System.currentTimeMillis();
        try {
            return invocation.proceed();
        } finally {
            long endTime = System.currentTimeMillis();
            long executionTime = endTime - startTime;
            if (executionTime > slowQueryThreshold) {
                StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
                String sql = statementHandler.getBoundSql().getSql();
                logger.warn("Slow query detected! SQL: {}, Execution time: {} ms", sql, executionTime);
            }
        }
    }

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

    @Override
    public void setProperties(Properties properties) {
        String threshold = properties.getProperty("slowQueryThreshold");
        if (threshold != null) {
            slowQueryThreshold = Long.parseLong(threshold);
        }
    }
}

3. 配置拦截器

在 MyBatis 的配置文件(如 mybatis-config.xml)中配置拦截器:

xml
<plugins>
    <plugin interceptor="com.yourcompany.yourproject.interceptor.SlowQueryInterceptor">
        <property name="slowQueryThreshold" value="1000" />
    </plugin>
</plugins>

将 com.yourcompany.yourproject.interceptor.SlowQueryInterceptor 替换为你实际的拦截器类的全限定名,slowQueryThreshold 为慢查询时间阈值,单位是毫秒。

总结

通过以上步骤,你可以在 MyBatis 中实现慢查询日志的打印。自定义拦截器会在 SQL 执行前后记录时间,当执行时间超过设定的阈值时,会将 SQL 语句和执行时间记录到日志中,方便你后续进行分析和优化。

mybatis 打印sql日志

# mybatis配置
mybatis:
# 搜索指定包别名
typeAliasesPackage: com.ltkj.ticket
# 配置mapper的扫描,找到所有的mapper.xml映射文件
mapperLocations: classpath:mapper/**/*.xml
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl 

或者:下面结合
在这里插入图片描述

在这里插入图片描述

### MyBatis 配置日志打印方法 在 MyBatis 中配置和打印日志可以通过多种方式实现,具体取决于项目的实际需求以及使用的日志框架。以下是几种常见的配置方法: #### 方法一:通过 `application.yml` 或 `application.properties` 配置 可以在 Spring Boot 项目中直接通过 `application.yml` 或 `application.properties` 文件配置 MyBatis日志打印功能。例如,在 `application.yml` 文件中添加以下内容: ```yaml mybatis: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl ``` 此配置将启用 MyBatis 的标准输出日志功能,SQL 语句将会打印到控制台[^2]。 此外,还可以通过设置特定的包路径为 `DEBUG` 级别来进一步控制日志输出。例如: ```yaml logging: level: com.threefivework.mymall.dao.mapper: DEBUG ``` 上述配置会将 `com.threefivework.mymall.dao.mapper` 包下的 SQL 日志级别设置为 `DEBUG`,从而确保相关 SQL 语句能够被打印出来[^1]。 #### 方法二:通过 `mybatis-config.xml` 配置 如果项目中使用了 `mybatis-config.xml` 文件,则可以在该文件中添加以下配置以开启日志打印功能: ```xml <settings> <!-- 打印 SQL 日志 --> <setting name="logImpl" value="STDOUT_LOGGING" /> </settings> ``` 此处的 `logImpl` 属性指定了 MyBatis 使用的日志实现方式,`STDOUT_LOGGING` 表示将日志输出到标准输出流中[^3]。 #### 方法三:通过日志框架配置 MyBatis 支持与多种日志框架集成,如 Log4j、Logback 等。如果项目中使用了 Logback 作为日志框架,则可以在 `logback-spring.xml` 文件中添加如下配置: ```xml <logger name="com.solin.springmvc.mapper" level="DEBUG" /> ``` 上述配置会将 `com.solin.springmvc.mapper` 包下的日志级别设置为 `DEBUG`,从而确保 SQL 语句能够被正确打印[^4]。 #### 方法四:通过编程方式配置 如果需要动态地配置 MyBatis日志功能,也可以通过编程方式进行设置。例如,在初始化 MyBatis 配置时,可以手动设置 `logImpl` 属性: ```java import org.apache.ibatis.session.Configuration; import org.apache.ibatis.logging.stdout.StdOutImpl; Configuration configuration = new Configuration(); configuration.setLogImpl(StdOutImpl.class); ``` 此代码片段会在运行时动态设置 MyBatis日志实现为标准输出。 ### 注意事项 - 配置日志级别时,建议仅在开发或调试阶段启用 `DEBUG` 级别的日志输出,避免在生产环境中产生过多日志信息。 - 如果项目中使用了其他日志框架(如 Log4j2),则需要根据具体的框架文档调整配置文件中的相关内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI小胖

您的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值