springboot【21】日志管理之1.5.x新特性:动态修改日志级别

来源:互联网 发布:cad2016简体中文版mac 编辑:程序博客网 时间:2024/06/05 15:23

          对于1.5.x版本的新特性列表读者可以直接查看官方博文:《Spring Boot 1.5.1 released》来进行了解。


loggers端点

        Spring Boot 1.5.x中引入的一个新的控制端点:/loggers,该端点将为我们提供动态修改Spring Boot应用日志级别的强大功能。该功能的使用非常简单,它依然延续了Spring Boot自动化配置的实现,所以只需要在引入了spring-boot-starter-actuator依赖的条件下就会自动开启该端点的功能(更多关于spring-boot-starter-actuator模块的详细介绍可见springboot【22】监控管理之Actuator监控端点 一文)。

下面通过一个实际示例来看看如何使用该功能:

  • pom.xml引入如下依赖(如果使用Intellij中的Spring Initializr的话直接在提示框中选下web和actuator模块即可)。

    <parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.1.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><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></dependencies>
  • 在应用主类中添加一个接口用来测试日志级别的变化,比如下面的实现:

    package com.lyd;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@SpringBootApplicationpublic 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);}}
  • 为了后续的试验顺利,在application.properties中增加一个配置,来关闭安全认证校验。

    management.security.enabled=false

    不然在访问/loggers端点的时候,会报如下错误:

    {  "timestamp": 1485873161065,  "status": 401,  "error": "Unauthorized",  "message": "Full authentication is required to access this resource.",  "path": "/loggers/com.didispace"}

测试验证

在完成了上面的构建之后,我们启动示例应用,并访问/test端点,我们可以在控制台中看到如下输出:


由于默认的日志级别为INFO,所以并没有输出DEBUG级别的内容。下面我们可以尝试通过/logger端点来将日志级别调整为DEBUG,比如,发送POST请求到/loggers/com.lyd端点,其中请求体Body内容为:

{    "configuredLevel": "DEBUG"}

重新访问/test端点,我们将在控制台中看到如下输出,在/test端点中定义的DEBUG日志内容被打印了出来:


可以看到,到这里为止,我们并没有重启过Spring Boot应用,而只是简单的通过调用/loggers端点就能控制日志级别的更新。除了POST请求之外,我们也可以通过GET请求来查看当前的日志级别设置,比如:发送GET请求到/loggers/com.lyd端点,我们将获得对于com.lyd包的日志级别设置:

{  "configuredLevel": "DEBUG",  "effectiveLevel": "DEBUG"}

也可以不限定条件,直接通过GET请求访问/loggers来获取所有的日志级别设置,这里就不列举具体返回,大家可以自行尝试。



下面是完整项目结构:



原创粉丝点击