springboot+mybatis-plus的logback+Slf4j日志配置及sql打印

第一步加入如下log包

// https://mvnrepository.com/artifact/org.projectlombok/lombok
compileOnly 'org.projectlombok:lombok:1.18.6'
annotationProcessor 'org.projectlombok:lombok:1.18.6'
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-logging
compile group: 'org.springframework.boot', name: 'spring-boot-starter-logging', version: '2.3.1.RELEASE'

 在resources下新建logback-spring.xml放在resources下springboot可自动装配。

如果想自定义可在mybatisplus配置中设置如下

# 加载全局的配置文件
configLocation: classpath:mybatis/mybatis-config.xml

logback-spring.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
    <contextName>logback</contextName>
    <!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->
    <property name="LOG_HOME" value="logs" />

    <!-- 彩色日志 -->
    <!-- 彩色日志依赖的渲染类 -->
    <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
    <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
    <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
    <!-- 彩色日志格式 -->
    <property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
    <!-- 控制台输出 -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!--日志级别过滤INFO以下-->
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<!--            <level>info</level>-->
            <!-- 过滤的级别 -->
            <level>debug</level>
        </filter>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
        </encoder>
    </appender>

    <!-- 按照每天生成日志文件 -->
    <appender name="FILE"  class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名-->
            <FileNamePattern>${LOG_HOME}/promotion.%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--日志文件保留天数-->
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
        <!--日志文件最大的大小-->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>10MB</MaxFileSize>
        </triggeringPolicy>
    </appender>
    <!-- 日志输出级别 -->
    <root level="debug">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </root>
    <root level="info">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </root>
<!--    mapper(sql)日志级别,放在yml控制-->
<!--    <logger name="com.example.gradle.mapper" level="debug" />-->


</configuration>

  

 mapper(sql)日志级别
logging:
  level:
    com.example.gradle.mapper: debug

 使用例子

@RestController
@RequestMapping("/pay-record")
@Slf4j
public class PayRecordController {

    @Autowired
    private IPayRecordService service;

    /**
     *  查询列表
     * @return
     */
    @GetMapping("/list")
    public AjaxResult list(PayRecord payRecord) {
        log.info("日志测试");
        LambdaQueryWrapper<PayRecord> wrapper = new QueryWrapper<PayRecord>().lambda();
        if(null != payRecord.getPayId()){
            wrapper.eq(PayRecord::getPayId,payRecord.getPayId());
        }

        return AjaxResult.success(service.list(wrapper));
    }

}

  打印出的log

2020-09-12 18:45:52.093  INFO 11740 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-09-12 18:45:52.256  INFO 11740 --- [           main] o.a.coyote.http11.Http11NioProtocol      : Starting ProtocolHandler ["http-nio-8080"]
2020-09-12 18:45:52.353  INFO 11740 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-09-12 18:45:52.365  INFO 11740 --- [           main] com.example.DemoApplication              : Started DemoApplication in 2.236 seconds (JVM running for 3.306)
2020-09-12 18:45:56.119  INFO 11740 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-09-12 18:45:56.123  INFO 11740 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-09-12 18:45:56.131  INFO 11740 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 8 ms
2020-09-12 18:45:56.171  INFO 11740 --- [nio-8080-exec-1] c.e.g.controller.PayRecordController     : 日志测试
2020-09-12 18:45:56.305  INFO 11740 --- [nio-8080-exec-1] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
2020-09-12 18:45:57.588 DEBUG 11740 --- [nio-8080-exec-1] c.e.g.mapper.PayRecordMapper.selectList  : ==>  Preparing: SELECT pay_id,receipt_by,dept_name,pay_time,remark,del_flag,paid_money,receipt_time,pay_money,pay_idnumber,update_by,pay_oddnumbers,ancestors,pay_name,project_content,nick_name,traceno,dept_id,receipt_remark,update_time,transdate,transtime,create_by,pay_phone,create_time,receipt_no,qr_code_url,pay_statusDes,pay_status,receipt_status FROM pay_record 
2020-09-12 18:45:57.620 DEBUG 11740 --- [nio-8080-exec-1] c.e.g.mapper.PayRecordMapper.selectList  : ==> Parameters: 
2020-09-12 18:45:57.714 DEBUG 11740 --- [nio-8080-exec-1] c.e.g.mapper.PayRecordMapper.selectList  : <==      Total: 1

  完美解决sql的打印

生产环境只需吧mapper日志级别改为info即可。

 

posted @ 2020-09-12 19:02  小尼  阅读(13084)  评论(0编辑  收藏  举报