springboot动态调整日志级别

1.springboot使用log4j2

springboot使用的common-logging,底层兼容各种日志框架如,log4j2,slf4,logback等,默认底层使用的是logback,我们可以去除logback的依赖,引入log4j2的starter,
如下:
在这里插入图片描述

2.指定日志配置文件和日志等级(此配置不限于log4j2,也适用于其他日志框架)

在resources目录下加入log4j2的xml配置文件,默认spring-boot会加载classpath下面的名为log4j2.xml,或log4j2-file.xml的日志配置文件。
在这里插入图片描述
也可以在spring的配置文件中指定需要加载的日志配置文件,以及动态调整各个目录的日志等级

logging:
  config: classpath:log4j2.xml
  level:
    com.ly: debug
    org.springframework : info

该参数可以通过系统参数,或启动参数,覆盖jar内的配置项。

java -jar -Dlogging.config="xxx" test.jar
java -jar test.jar --logging.config="xxx"

3.通过springboot-actuator动态调整日志级别(适用于生产环境)

spring-boot-actuator是springboot的一个监控工具,它可以以http或JMX的方式暴露一些endPoint,内置的endpoint有 health,info,beans,loggers等。
我们可以通过loggers来动态调整日志级别,无需重启服务。

如果是想使用webEndPoint的话,项目必须包含web-starter相关的依赖,因为actuator 的httpEndPoint是以mvc的方式集成的。

3.1 在pom文件中引入依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

3.2 在配置文件中开启loggers的endPoint端点

management:
  endpoints:
    web:
      exposure:
        include: loggers

3.3 发起http请求改变日志级别

URI默认是 /actuator+endpoint+包名

$ curl 'http://localhost:8080/actuator/loggers/com.example' -i -X POST 
    -H 'Content-Type: application/json' 
    -d '{"configuredLevel":"debug"}'

原理可以看LoggersEndPoint的实现
在这里插入图片描述

4.spring boot日志初始化原理

在这里插入图片描述
有个loggingApplicationListener的监听器,监听了spring的事件,读取了spring容器中的日志配置,进行了日志的初始化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值