目录
创建 log4j.properties 配置文件放在src/main/resources目录下
剔除SpringBoot自带的日志
在项目的pom.xml文件中做如下更改
<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>
在pom.xml文件中引入log4j
<!-- 引入日志依赖 抽象层与实现层-->
<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>
创建 log4j.properties 配置文件放在src/main/resources目录下
并加入如下配置:
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=%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
使用案例
package com.imooc.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @description: 测试Controller
* @author: WhiteCrowZHZ
* @date: 2022/2/14 21:22
*/
@RestController
public class HelloController {
// 创建logger
private final static Logger logger = LoggerFactory.getLogger(HelloController.class);
@GetMapping("/hello")
public Object hello() {
// 日志打印
logger.debug("debug");
logger.info("info");
logger.warn("warn");
logger.error("error");
return "hello world~";
}
}
日志打印效果