springboot中动态切换日志输出级别

tech2025-02-04  14

springboot中动态切换log日志级别   (依靠actuator监控组件) 1、pom.xml配置

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> <version>2.1.7.RELEASE</version> </dependency> <!-- 可选--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>

2、application.yml配置

server: port: 8082 servlet: context-path: / #管理端点 management: #server: # port: 7001 # address: 127.0.0.1 endpoint: shutdown: enabled: true endpoints: web: base-path: /actuator exposure: #include: "*" #loggers include: - info - health - loggers - mappings - beans - env - shutdown logging: level: root: INFO org.springframework.web: INFO org.springframework.jdbc: INFO com.tingcream: INFO #项目包日志级别 file: /log/logdemo/logdemo.log

3、 项目中代码中记录日志

import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @EnableAspectJAutoProxy(exposeProxy=true,proxyTargetClass=true) @SpringBootApplication @Slf4j public class LogDemoApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(LogDemoApplication.class, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(LogDemoApplication.class); } @RequestMapping("/") public String index(){ log.info("这是一条info级别日志"); log.debug("这是一条debug级别日志"); return "hello springboot!"; } }

启动springboot项目后, 访问 http://localhost:8082/ 发现只输出了一条info级别的日志。 curl -X GET   http://192.168.0.14:8082/actuator/loggers/com.tingcream    发现com.tingcream 的日志level配置的是info,所以debug级别的日志才没有输出过来

现在,我们使用curl 命令将com.tingcream包的日志level修改为debug  curl -X POST http://192.168.0.14:8082/actuator/loggers/com.tingcream  -H "Content-type: application/json"  -d "{\"configuredLevel\":\"DEBUG\"}"  

再次请求首页,发现info和debug级别的日志都输出来了。。

附,actuator常用的端点: http://localhost:8082/actuator/health #健康 http://localhost:8082/actuator/info  #信息  获取的是application.yml中的info节点的信息,如info.app.name=xxx http://localhost:8082/actuator/beans  #spring容器中的bean http://localhost:8082/actuator/env  #环境变量 http://localhost:8082/actuator/metrics #指标 http://localhost:8082/actuator/mappings # controller层请求映射 http://localhost:8082/actuator/configprops # application.yml中的配置属性 优雅停机 curl -X POST http://localhost:8082/actuator/shutdown

 

最新回复(0)