1.添加依赖
把spring-boot-starter-logging的依赖排除掉,只使用slf4j-log4j12
<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.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>
2.在需要的类中添加声明并输出logger
final static Logger logger = LoggerFactory.getLogger(HelloController.class);
@GetMapping("/hello")
public Object hello() {
logger.debug("debug: hello~");
logger.info("info: hello~");
logger.warn("warn: hello~");
logger.error("error: hello~");
return "Hello World~";
}
3.添加配置文件log4j.properties
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
#输出文件设置,DailyRollingFileAppender按照每天日期生成
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-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
日志行
2020-12-29 18:05:51 INFO MapperCacheDisabler:83 - Clear EntityHelper entityTableMap cache.
日志文件