springboot2.X动态修改log4j2日志级别
利用springboot提供的 spring-boot-starter-actuator 包可以实现动态修改log4j2日志级别的功能
添加依赖
添加依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
修改配置
修改springboot配置文件application.yml,添加如下配置
management:
endpoints:
web:
exposure:
include: 'loggers'
查询日志级别
利用postman GET请求地址 http://localhost:8080/ecs-exporter/actuator/loggers
得到结果
{
"levels": [
"OFF",
"FATAL",
"ERROR",
"WARN",
"INFO",
"DEBUG",
"TRACE"
],
"loggers": {
"ROOT": {
"configuredLevel": "INFO",
"effectiveLevel": "INFO"
},
"com": {
"configuredLevel": "DEBUG",
"effectiveLevel": "DEBUG"
}
}
}
从上面结果中可以看到每个包对应的日志级别,查看指定包对应日志级别可以在url后面拼接对应的包全路径
如:http://localhost:8080/ecs-exporter/actuator/loggers/com
{
"configuredLevel": "DEBUG",
"effectiveLevel": "DEBUG"
}
修改
ROOT
级别不可动态修改,可以修改每个包的日志级别
利用postman POST请求地址 http://localhost:8080/ecs-exporter/actuator/loggers/对应包
请求体
{
"configuredLevel": "info"
}
再次查看日志级别,已经变更
{
"levels": [
"OFF",
"FATAL",
"ERROR",
"WARN",
"INFO",
"DEBUG",
"TRACE"
],
"loggers": {
"ROOT": {
"configuredLevel": "INFO",
"effectiveLevel": "INFO"
},
"com": {
"configuredLevel": "INFO",
"effectiveLevel": "INFO"
}
}
}
对应log4j.yml配置
loggers:
logger:
- # 以com开头的logger
name: com
level: info
additivity: false
appenderRef:
- ref: default_console # 将日志信息输出到控制台
root:
level: info
additivity: false
appenderRef:
- ref: default_console