Spring Boot動態修改日誌級別
阿新 • • 發佈:2018-12-19
一 點睛
1 loggers端點
該端點將為我們提供動態修改Spring Boot應用日誌級別的強大功能。該功能的使用非常簡單,它依然延續了Spring Boot自動化配置的實現,所以只需要在引入了spring-boot-starter-actuator依賴的條件下就會自動開啟該端點的功能。
二 實戰
1 引入依賴包
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
2 配置application.properties
關閉安全認證校驗
management.security.enabled=false
3 啟動類
package com.didispace; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @SpringBootApplication public class DemoApplication { private Logger logger = LoggerFactory.getLogger(getClass()); @RequestMapping(value = "/test", method = RequestMethod.GET) public String testLogLevel() { logger.debug("Logger Level :DEBUG"); logger.info("Logger Level :INFO"); logger.error("Logger Level :ERROR"); return ""; } public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
三 測試
1 啟動應用程式
3 控制檯輸出——由於預設的日誌級別為INFO,所以並沒有輸出DEBUG級別的內容。
2018-11-03 15:13:50.655 INFO 59148 --- [nio-8080-exec-1] ication$$EnhancerBySpringCGLIB$$302a5f35 : Logger Level :INFO
2018-11-03 15:13:50.655 ERROR 59148 --- [nio-8080-exec-1] ication$$EnhancerBySpringCGLIB$$302a5f35 : Logger Level :ERROR
4 postman傳送如下訊息配置DEBUG
傳送POST請求到/loggers/com.didispace端點
{
"configuredLevel": "DEBUG"
}
6 控制檯輸出——從日誌輸出,可知動態修改生效了
2018-11-03 15:17:46.718 DEBUG 59148 --- [nio-8080-exec-7] ication$$EnhancerBySpringCGLIB$$302a5f35 : Logger Level :DEBUG
2018-11-03 15:17:46.718 INFO 59148 --- [nio-8080-exec-7] ication$$EnhancerBySpringCGLIB$$302a5f35 : Logger Level :INFO
2018-11-03 15:17:46.718 ERROR 59148 --- [nio-8080-exec-7] ication$$EnhancerBySpringCGLIB$$302a5f35 : Logger Level :ERROR