依赖jar包:
在创建Spring Boot工程时,我们引入了spring-boot-starter,其中包含了spring-boot-starter-logging,该依赖内容就是Spring Boot默认的日志框架Logback,所以我们在引入log4j之前,需要先排除该包的依赖,再引入log4j的依赖,就像下面这样:
<!-- 忽略自带的日志框架. -->
<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>
<!-- log4j. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
</dependency>
配置log4j-spring.properties
写到控制台
# Global logging configuration
log4j.rootLogger=INFO,stdout
# MyBatis logging configuration...
log4j.logger.com.yanchengtech.app.mapper=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
注: 下图红框中定义了打印的接口在哪里
写到文件:
# Global logging configuration
log4j.rootCategory=INFO,stdout,file
# MyBatis logging configuration...
log4j.logger.com.yanchengtech.app.mapper=DEBUG
# Console output...
#log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.file=D://logs/springboot.log
log4j.appender.file.DatePattern='.'yyyy-MM-dd
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n
运行结果:
DEBUG [http-nio-8070-exec-2] - ==> Preparing: SELECT count(0) FROM activity WHERE 1 = 1 AND status = ?
DEBUG [http-nio-8070-exec-2] - ==> Parameters: 3(Integer)
DEBUG [http-nio-8070-exec-2] - <== Total: 1
DEBUG [http-nio-8070-exec-2] - ==> Preparing: select act_id,product_name,picture_url,dis_ser1,unit_price,apply_amount,apply_count,buy_sum,freight from activity WHERE 1=1 and status = ? order by time_3 desc
DEBUG [http-nio-8070-exec-2] - ==> Parameters: 3(Integer)
DEBUG [http-nio-8070-exec-2] - <== Total: 44