软件编程
位置:首页>> 软件编程>> java编程>> springboot动态调整日志级别的操作大全

springboot动态调整日志级别的操作大全

作者:forwardMyLife  发布时间:2023-11-03 19:31:12 

标签:springboot,日志级别

1.springboot使用log4j2

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

springboot动态调整日志级别的操作大全

2.指定日志配置文件和日志等级

(此配置不限于log4j2,也适用于其他日志框架)

在resources目录下加入log4j2的xml配置文件,默认spring-boot会加载classpath下面的名为log4j2.xml,或log4j2-file.xml的日志配置文件。

springboot动态调整日志级别的操作大全

也可以在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的实现

springboot动态调整日志级别的操作大全

4.spring boot日志初始化原理

springboot动态调整日志级别的操作大全

有个loggingApplicationListener的 * ,监听了spring的事件,读取了spring容器中的日志配置,进行了日志的初始化。

来源:https://blog.csdn.net/lucky_ly/article/details/120693006

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com