springboot整合mybatis-plus的sql输出到日志文件上

springboot整合mybatis-plus的sql输出到日志文件上

在平时的日常开发中,我们希望sql打印在控制台上,只要如下配置即可

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

但是在生产中如果希望sql输出到日志文件上,有几种方式可以实现,下面我就用项目中常用的两种方式(不引入第三方依赖)

一、修改yml文件配置即可

缺点:需要把指定包开启debug级别,而在生产中,日志级别一般都是info级别的

1、配置输出日志文件上,springboot默认的日志框架是logback,
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl
2、修改日志输出级别

因为日志打印的实现类JsqlParserCountOptimize,上面做了日志级别的判断,如果是debug级别才会打印sql

在这里插入图片描述

logging:
  level:
    com.baomidou.mybatisplus: DEBUG

3、修改项目中mapper包的日志输出级别

因为对我们项目中的mapper的对数据库操作的类做了动态代理,在org.apache.ibatis.executor.BaseExecutor也做了debug级别的限制,所以也需要设置为debug级别
在这里插入图片描述

logging:
  level:
    com.baomidou.mybatisplus: DEBUG
    com.xl.finance.module: DEBUG

注意:如果mapper在不同的包下,路径不能用通配符(*)来代替,需要把包的路径范围调整为更大即可。

配置好在项目的debug文件可以看到如下的效果

在这里插入图片描述

二、引入p6spy依赖

1、引入p6spy的依赖包

maven仓库的版本:https://mvnrepository.com/artifact/p6spy/p6spy

<!-- https://mvnrepository.com/artifact/p6spy/p6spy -->
<dependency>
    <groupId>p6spy</groupId>
    <artifactId>p6spy</artifactId>
    <version>3.9.1</version>
</dependency>

2、修改jdbc连接驱动

主要是修改:driver-class-namejdbc-url

jdbc-url: jdbc:p6spy:mysql://${
    
    db.host}:${
    
    db.port}/${
    
    db.name}?useSSL=false&allowMultiQueries=true&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
driver-class-name: com.p6spy.engine.spy.P6SpyDriver

3、新建一个以spy.properties的文件

#日志格式
appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 格式化
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
# 取消JDBC的url前缀
useprefix=true

然后在我们项目的info的日志文件可以看到如下的效果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq798867485/article/details/129734277