springboot使用tk.mybatis通用mapper使用log4j打印sql

  • Post author:
  • Post category:其他


springboot使用log4j打日志,非常简单,首页需要在pom文件中屏蔽掉默认的日志方式spring-boot-starter-logging,并引入log4j相关依赖(如果其他依赖也使用了跟log4j不相容的也排除掉即可):

<!-- log4j start -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j</artifactId>
    <version>1.3.8.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
</dependency>
<!-- log4j end -->

在项目目录下创建res文件夹,创建log4j.properties文件,你也可以放到src/main/resources下面,此时不需要再加如下的语句:

PropertyConfigurator.configure(System.getProperty("logging.config", "res/log4j.properties"));

我们这里使用res目录是考虑到不同的环境可能需要不同的日志级别,只需要修改res目录下的配置即可。在启动类中这样设置:

@EnableAutoConfiguration
@ComponentScan(basePackages = "cn.lovecto.promotion")
@MapperScan(basePackages = "cn.lovecto.promotion.dao.mapper")//数据库访问mapper接口所在包名
@EnableScheduling
@EnableAsync
@EnableTransactionManagement
public class Application {

    public static void main(String[] args) {
        //放到自定义的res目录下的方式
        PropertyConfigurator.configure(System.getProperty("logging.config", "res/log4j.properties"));
        SpringApplication.run(Application.class, args);
    }

}

log4j.properties在springboot中的配置并没有什么特殊说明的,由于我们使用tk.mybatis通用mapper,如果要打印日志查看sql,可以在log4j.properties中加入如下内容即可。

log4j.rootLogger=INFO,err,stdout
#数据库访问mapper接口所在包日志级别
log4j.logger.cn.lovecto.promotion.dao.mapper=DEBUG,db

#db.log,每天一个文件
log4j.logger.db=DEBUG,db
log4j.appender.db=org.apache.log4j.DailyRollingFileAppender
log4j.appender.db.Threshold=DEBUG
log4j.appender.db.File=./logs/db.log
log4j.appender.db.layout=org.apache.log4j.PatternLayout
log4j.appender.db.layout.ConversionPattern=%5p %d{yyyy-MM-dd HH\:mm\:ss} [%F\:%L] %m %n

运行单元测试,控制台和db.log中打印出:

DEBUG 2018-08-03 15:52:28 [BaseJdbcLogger.java:159] ==>  Preparing: SELECT id,promotion_name,advance_start_time,booking_start_time,booking_end_time,checkin_start_time,checkin_end_time,promotion_type,promotion_value,promotion_icon,remark,enable_inventory,inventory,promotion_price_icon,inventory_factor,use_coupon,max_ordernum,enable_refund,refund_percent,quantity_limit,status FROM promotion WHERE ( booking_start_time >= ? and booking_end_time < ? )  
DEBUG 2018-08-03 15:52:28 [BaseJdbcLogger.java:159] ==> Parameters: 2018-08-03 15:52:28.123(Timestamp), 2018-08-03 15:52:28.123(Timestamp) 
DEBUG 2018-08-03 15:52:28 [BaseJdbcLogger.java:159] <==      Total: 0