Spring Cloud Spring Boot mybatis分布式微服务云架构(四十四)动态修改日志级别(1)

loggers端点

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

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

  • 构建一个基础的Spring Boot应用。如果您对于如何构建还不熟悉,可以参考《使用Intellij中的Spring Initializr来快速构建Spring Boot/Cloud工程》一文。

  • 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>

    在应用主类中添加一个接口用来测试日志级别的变化,比如下面的实现:

    @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);
    	}
      
    }

    为了后续的试验顺利,在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"
    }

    源码来源

猜你喜欢

转载自my.oschina.net/u/3776687/blog/1633177
今日推荐