1、pom文件的依赖配置中,去掉spring boot默认的log配置,引入log4j2依赖包:
<!-- log related -->
<dependency> <!-- exclude掉spring-boot的默认log配置 -->
<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> <!-- 引入log4j2依赖 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency> <!-- 加上这个才能辨认到log4j2.yml文件 -->
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
<!-- end of log related -->
2、log4j2.yml文件配置(放置在resources文件夹中):
在application.yml中配置读取自定义的yml文件
#日志配置
logging:
config: classpath:log4j2.yml
log4j2.yml文件的内容
Configuration:
status: warn
Properties: # 定义全局变量
Property: # 缺省配置(用于开发环境)。其他环境需要在VM参数中指定,如下:
#测试:-Dlog.level.console=warn -Dlog.level.xjj=trace
#生产:-Dlog.level.console=warn -Dlog.level.xjj=info
- name: log.level.console
value: trace
# - name: log.level.xjj
# value: trace
- name: log.path
#value: /opt/logs
value: F:\Program Files\IdeaProjects\mgspringboot\src\main\resources\log4j2s
- name: project.name
value: my-spring-boot
Appenders:
Console: #输出到控制台
name: CONSOLE
target: SYSTEM_OUT
ThresholdFilter:
level: ${sys:log.level.console} # “sys:”表示:如果VM参数中没指定这个变量值,则使用本文件中定义的缺省全局变量值
onMatch: ACCEPT
onMismatch: DENY
PatternLayout:
pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n"
RollingFile: # 输出到文件,超过128MB归档
- name: ROLLING_FILE
ignoreExceptions: false
fileName: ${log.path}/${project.name}.log
filePattern: "${log.path}/$${date:yyyy-MM}/${project.name}-%d{yyyy-MM-dd}-%i.log.gz"
PatternLayout:
pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n"
Policies:
SizeBasedTriggeringPolicy:
size: "128 MB"
DefaultRolloverStrategy:
max: 1000
Loggers:
Root:
# 共有8个级别,按照从低到高为:ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF 选择all则输出全部的日志
level: ALL
AppenderRef:
- ref: CONSOLE
- ref: ROLLING_FILE
# Logger: # 为com.xjj包配置特殊的Log级别,方便调试
# - name: com.xjj
# additivity: false
# level: ${sys:log.level.xjj}
# AppenderRef:
# - ref: CONSOLE
# - ref: ROLLING_FILE
3、测试用例:
@RunWith(SpringRunner.class)
@SpringBootTest
public class MgspringbootApplicationTests {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
@Test
public void contextLoads() {
logger.trace("I am trace log.");
logger.debug("I am debug log.");
logger.warn("I am warn log.");
logger.error("I am error log.");
}
}
输出
选择为all才会输出四条,但是输出的日志会很多,一般我们选择到info级别,将警告和错误输出,更低级的日志不打印