Java: 动态更新Log4J2日志级别

Log4J的日志级别

下表示Log4J内置的日志级别.

标准级别数字级别
OFF0
FATAL100
ERROR200
WARN300
INFO400
DEBUG500
TRACE600
ALLInteger.MAX_VALUE

java标志
image-2871

使用Spring Boot

完整源码地址: Gitee仓库

例子中使用了Spring Boot,而在Spring Boot中,支持的日志级别为: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF .

在Spring Boot中,配置Log4J2很简单,只需要简单几步就可以完成.

当然,Spring Boot还支持其它日志系统,例如: Commons Logging(Spring Boot默认的日志系统),Logback,Log4J2,Java Util Logging.并且针对Logback,Log4J2,Java Util Logging提供了默认自动配置.

日志级别与颜色映射

在Spring Boot中,提供了日志级别与颜色映射,如下:

级别颜色
FATAL红色
ERROR红色
WARN黄色
INFO绿色
DEBUG绿色
TRACE绿色

源码

完整源码地址: Gitee仓库

如果要在Spring Boot中配置Log4J2,只需要在pom.xml中配置相关依赖即可:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter</artifactId>
	<exclusions>
		<exclusion>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-logging</artifactId>
		</exclusion>
	</exclusions>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<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.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<version>1.18.8</version>
</dependency>

这里需要排除spring-boot-starter-logging,因为默认的spring-boot-starter-logging和Log4J2会冲突.

在这里引入Lombok是因为可以自动生成Log4J2的实例,简化使用.

引入actuator是因为我们需要动态修改日志级别.

使用:

import lombok.extern.log4j.Log4j2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@SpringBootApplication
@RestController
@Log4j2
public class Log4jlevelupdatedemoApplication {


    @RequestMapping("/")
    public Map<String,String> hello(){
        log.trace("test trace");
        log.debug("test debug");
        log.warn("test warn");
        log.info("test info");
        log.error("test error");
        return Map.of("Hello","Java");
    }

    public static void main(String[] args) {
        SpringApplication.run(Log4jlevelupdatedemoApplication.class, args);
    }

}

需要注意: 每次重启服务器,日志级别都会被重置为默认级别.

操作步骤

1 . 浏览器访问: http://localhost:8080/ ,会在【控制台】输出测试日志:

2019-08-02 10:10:11.489 WARN 15340 — [nio-8080-exec-1] x.s.l.Log4jlevelupdatedemoApplication : test warn
2019-08-02 10:10:11.490 INFO 15340 — [nio-8080-exec-1] x.s.l.Log4jlevelupdatedemoApplication : test info
2019-08-02 10:10:11.490 ERROR 15340 — [nio-8080-exec-1] x.s.l.Log4jlevelupdatedemoApplication : test error

2 . 浏览器访问: http://localhost:8080/actuator/loggers ,可以看到目前的日志级别配置;

3 . 在Postman中新建一个POST请求,地址为: http://localhost:8080/actuator/loggers/ROOT , 参数为: Body -> raw -> JSON(application/json) ,内容为:

TRACE为日志级别,可选值为: TRACE, DEBUG, INFO, WARN, ERROR, FATAL,OFF.

{
“configuredLevel”: “TRACE”
}

请求之后,不会返回任何数据.再次发起[1]请求,之后即可在控制台看到修改后的数据.

实现原理

  1. 请求会抵达 [1]org.springframework.boot.actuate.logging.LoggersEndpoint 该类为loggers端点的处理类;
  2. 调用[1]类的configureLogLevel方法,在此方法中会调用当前日志系统的抽象父类(org.springframework.boot.logging.LoggingSystem),该类有多个子类,其中一个子类为:[2]org.springframework.boot.logging.log4j2.Log4J2LoggingSystem,就会取到该类;
  3. 调用[2]类中的setLogLevel方法,在此方法中,会将我们传递给Spring Boot的日志级别转换为Log4J2对应的日志级别;
  4. 如果配置对象为空的话,则会新建一个配置,反之则直接设置给当前配置;
  5. 最后调用org.apache.logging.log4j.core.LoggerContext的updateLoggers方法刷新配置.

完整源码地址: Gitee仓库

Spring Boot: 起步依赖的实现原理

Spring Boot 版本: 2.1.4.RELEASE

简要说明

Spring Boot依赖项管理定义:

Spring Boot中在spring-boot-dependencies*.jar的pom.xml中定义了所依赖的依赖项的名称和版本信息.(如果要覆盖Spring Boot默认引用的版本信息,可以在自己的pom.xml文件中定义与spring-boot-dependencies中的pom.xml中版本名称一致的配置,配置自己的版本号即可.)

pom.xml所在网址:

https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot-dependencies/pom.xml

替换Spring Boot配置的默认Thymeleaf版本

<properties>
		<!-- 省略上面的版本定义... -->
		<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
		<thymeleaf-extras-springsecurity.version>3.0.4.RELEASE</thymeleaf-extras-springsecurity.version>
		<thymeleaf-layout-dialect.version>2.4.1</thymeleaf-layout-dialect.version>
		<thymeleaf-extras-data-attribute.version>2.0.1</thymeleaf-extras-data-attribute.version>
		<thymeleaf-extras-java8time.version>3.0.4.RELEASE</thymeleaf-extras-java8time.version>
		<!-- 省略下面的版本定义...end -->
	</properties>

替换thymeleaf的版本,在自己的pom.xml文件中定义:

<properties>
		<!-- 省略上面的版本定义...下面是示例版本号,实际可能并不存在5.X版本的信息 -->
		<thymeleaf.version>5.0.11.RELEASE</thymeleaf.version>
		<!-- 省略下面的版本定义...end -->
	</properties>

java标志
image-2809

起步依赖的特点

  1. 直接面向功能;
  2. 一站获取所有相关依赖,不再复制粘贴
  3. 官方的Starters

    命名: spring-boot-starter-*

    起步依赖实现原理

    其实质就是通过Maven依赖管理来实现起步依赖.

    例如:要使用jdbc,只需要引入:spring-boot-starter-jdbc,而spring-boot-starter-jdbc的pom.xml文件是如下定义的:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    	<parent>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starters</artifactId>
    		<version>${revision}</version>
    	</parent>
    	<artifactId>spring-boot-starter-jdbc</artifactId>
    	<name>Spring Boot JDBC Starter</name>
    	<description>Starter for using JDBC with the HikariCP connection pool</description>
    	<properties>
    		<main.basedir>${basedir}/../../..</main.basedir>
    	</properties>
    	<dependencies>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>com.zaxxer</groupId>
    			<artifactId>HikariCP</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-jdbc</artifactId>
    		</dependency>
    	</dependencies>
    </project>

    也就是Spring Boot在Maven的pom.xml文件里面引入了我们自己之前需要引入的Maven依赖.

    继承关系

    spring-boot-starter-jdbc继承了spring-boot-starters;
    而spring-boot-starters继承了spring-boot-parent;
    而spring-boot-parent继承了spring-boot-dependencies;
    spring-boot-dependencies继承了spring-boot-build.

    继承关系如下图(最上面是最底层的):

    Spring Boot起步依赖
    image-2810

Java: Spring Boot自动配置的实现原理

Spring Boot 版本: 2.1.4.RELEASE

配置了内存数据库EmbeddedDatabaseConnection 加载.

Java HotSpot(TM) 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended

自动配置: 基于CLASSPATH上出现的类,application.properties或者环境上下文出现的配置.作为依据,对spring-boot做出自动配置.

代码在:spring-boot-autoconfiguration包中.

开启自动配置: @EnableAutoConfiguration

排除指定的类: exclude=Class[]

java标志
image-2773

自动配置实现原理

使用各种条件注解

  1. @Conditional
  2. @ConditionalOnClass
  3. @ConditionalOnBean
  4. @ConditionalMissingBean
  5. @ConditionalOnProperty
  6. ……

加载META-INF/spring.factories文件中的类

@EnableAutoConfiguration注解中,引入了AutoConfigurationImportSelector在getCandidateConfigurations()方法中,使用了SpringFactoriesLoader类加载META-INF/spring.factories配置文件,并指定需要加载的配置键为AutoConfigurationImportSelector类的:getSpringFactoriesLoaderFactoryClass()方法的返回值,也就是EnableAutoConfiguration.class;

也就是通过这个方法,SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());获取到需要自动配置的类的信息.

在Spring Boot中,META-INF/spring.factories的文件内容如下:

其中org.springframework.boot.autoconfigure.EnableAutoConfiguration下面的条目是Spring Boot提供的自动配置的类:

# Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\
org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener

# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.autoconfigure.BackgroundPreinitializer

# Auto Configuration Import Listeners
org.springframework.boot.autoconfigure.AutoConfigurationImportListener=\
org.springframework.boot.autoconfigure.condition.ConditionEvaluationReportAutoConfigurationImportListener

# Auto Configuration Import Filters
org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\
org.springframework.boot.autoconfigure.condition.OnBeanCondition,\
org.springframework.boot.autoconfigure.condition.OnClassCondition,\
org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.cloud.CloudServiceConnectorsAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration,\
org.springframework.boot.autoconfigure.elasticsearch.rest.RestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
org.springframework.boot.autoconfigure.reactor.core.ReactorCoreAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityRequestMatcherProviderAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\
org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration

# Failure analyzers
org.springframework.boot.diagnostics.FailureAnalyzer=\
org.springframework.boot.autoconfigure.diagnostics.analyzer.NoSuchBeanDefinitionFailureAnalyzer,\
org.springframework.boot.autoconfigure.jdbc.DataSourceBeanCreationFailureAnalyzer,\
org.springframework.boot.autoconfigure.jdbc.HikariDriverConfigurationFailureAnalyzer,\
org.springframework.boot.autoconfigure.session.NonUniqueSessionRepositoryFailureAnalyzer

# Template availability providers
org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider=\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerTemplateAvailabilityProvider,\
org.springframework.boot.autoconfigure.mustache.MustacheTemplateAvailabilityProvider,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAvailabilityProvider,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafTemplateAvailabilityProvider,\
org.springframework.boot.autoconfigure.web.servlet.JspTemplateAvailabilityProvider

Java: Spring Boot Actuator源码分析

简述

Actuator相关代码在spring-boot-actuator-[version].jar下面.

  1. DefaultListableBeanFactory.getBeanNamesForAnnotation() : 按照Annotation类名来获取Bean实例名;
  2. EndpointDiscoverer.createEndpointBeans() : 按照获取到的Bean实例名创建EndpointBean
  3. AbstractWebMvcEndpointHandlerMapping.initHandlerMethods() : 根据刚才查找到的enpoints列表进行注册.
  4. AbstractWebMvcEndpointHandlerMapping:createRequestMappingInfo():创建url信息(类似于@RequestMapping)
  5. OnEnabledEndpointCondition.getMatchOutcome() : 获取配置文件中management.endpoint.[id].enabled的值,[id]为变量值,类似management.endpoint.shutdown.enabled.

java标志
image-2746

端点及处理方法在应用启动时初始化

注册端点处理方法处理流程是:

  1. org.springframework.boot.actuate.endpoint.annotation.EndpointDiscoverer:getEndpoints()
  2. org.springframework.boot.actuate.endpoint.annotation.EndpointDiscoverer:discoverEndpoints()
  3. org.springframework.boot.actuate.endpoint.annotation.EndpointDiscoverer:convertToEndpoints(Collection endpointBeans)
  4. org.springframework.boot.actuate.endpoint.annotation.EndpointDiscoverer:convertToEndpoint(EndpointBean endpointBean)
  5. org.springframework.boot.actuate.endpoint.annotation.EndpointDiscoverer:addOperations(MultiValueMap indexed, EndpointId id,
    Object target, boolean replaceLast)
  6. org.springframework.boot.actuate.endpoint.annotation.DiscoveredOperationsFactory:createOperations(EndpointId id, Object target)
  7. 待续.

获取端点处理方法在:

org.springframework.core.MethodIntrospector:selectMethods();

在端点处理类(比如:org.springframework.boot.actuate.health.HealthEndpoint)的方法上添加@ReadOperation(GET)、@WriteOperation(POST)、@DeleteOperation(DELETE)可以暴露该方法到路由中,同时可以在方法参数上添加@Selector指定子端点(例如:org.springframework.boot.actuate.health.HealthEndpoint:healthForComponent(@Selector String component)方法)


WebEndpointProperties: 获取配置文件中actuator服务的前缀.

Java:Spring Boot Actuator-Shutdown端点分析

java标志
image-2744

Spring Boot 版本: 2.1.3.RELEASE

处理类: org.springframework.boot.actuate.context.ShutdownEndpoint
处理方法: shutdown()

1. 首先检查应用上下文是否为空,为空则返回无可关闭应用,不为空则继续执行;
2. 返回关闭消息,并且新开一个线程,调用实际的关闭应用方法(this.context.close()),并设置500毫秒之后关闭应用.