spring boot (4) 使用log4 打印日志
1.排除spring boot 原有的日志依赖
在创建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>
2.引入日志依赖 抽象层 与 实现层
<!--引入日志依赖 抽象层 与 实现层--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.21</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.21</version> </dependency>
3. 配置:
log4j.rootLogger=DEBUG,stdout,file log4j.additivity.org.apache=true log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.threshold=INFO log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%-5p %c{1}:%L - %m%n log4j.appender.file=org.apache.log4j.DailyRollingFileAppender log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.DatePattern='.'yyyy-MM-dd-HH-mm log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n log4j.appender.file.Threshold=INFO log4j.appender.file.append=true log4j.appender.file.File=/workspaces/logs/foodie-api/imooc.log
4.编写测试类
package com.imooc.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import springfox.documentation.annotations.ApiIgnore; @ApiIgnore //@Controller @RestController public class Hello { final static Logger logger = LoggerFactory.getLogger(Hello.class); @GetMapping("/hello111") public Object hello() { logger.debug("debug: hello~"); logger.info("info: hello~"); logger.warn("warn: hello~"); logger.error("error: hello~"); return "hello world1"; } }
效果:
越努力越幸运