【问题标题】:Enable logging in spring boot actuator health check API在 Spring Boot 执行器健康检查 API 中启用日志记录
【发布时间】:2019-03-04 05:44:31
【问题描述】:

我正在为我的project 使用 Spring boot Actuator API,它有一个健康检查端点,并通过以下方式启用它:

management.endpoints.web.base-path=/
management.endpoints.web.path-mapping.health=healthcheck

提到here

现在我想在上面/healthcheck 的状态失败时在我的应用程序日志文件中启用日志,并从该端点打印整个响应。

实现这一目标的正确方法是什么?

【问题讨论】:

    标签: java spring-boot logging spring-boot-actuator


    【解决方案1】:

    最好的方法是使用@EndpointWebExtension 扩展执行器端点。您可以执行以下操作;

    @Component
    @EndpointWebExtension(endpoint = HealthEndpoint.class)
    public class HealthEndpointWebExtension {
    
        private HealthEndpoint healthEndpoint;
        private HealthStatusHttpMapper statusHttpMapper;
    
        // Constructor
    
        @ReadOperation
        public WebEndpointResponse<Health> health() {
            Health health = this.healthEndpoint.health();
            Integer status = this.statusHttpMapper.mapStatus(health.getStatus());
            // log here depending on health status.
            return new WebEndpointResponse<>(health, status);
        }
    }
    

    更多关于执行器端点扩展here,在4.8。扩展现有端点

    【讨论】:

    • 在spring-boot-actuator 2.2.5 中,HealthEndpoint.class 的扩展似乎已经在org.springframework.boot.actuate.autoconfigure.health.HealthEndpointWebExtensionConfiguration 中作为org.springframework.boot.actuate.health.HealthEndpointWebExtension 类型的Bean 存在/定义。不允许对同一个HealthEndpoint 拥有多个扩展名。 Spring Boot 应用程序无法启动。这段代码对任何人都有效吗?
    • @madhav-turangi 我设法通过扩展 ReactiveHealthEndpointWebExtension(registry, groups) 来做到这一点。然后像上面一样添加注释。
    【解决方案2】:

    如果使用 Webflux,这在 Kotlin 中对我有用

    @Component
    @EndpointWebExtension(endpoint = HealthEndpoint::class)
    class LoggingReactiveHealthEndpointWebExtension(
          registry: ReactiveHealthContributorRegistry,
          groups: HealthEndpointGroups
    ) : ReactiveHealthEndpointWebExtension(registry, groups) {
    
    companion object {
        private val logger = LoggerFactory.getLogger(LoggingReactiveHealthEndpointWebExtension::class.java)
    }
    
    override fun health(
        apiVersion: ApiVersion?,
        securityContext: SecurityContext?,
        showAll: Boolean,
        vararg path: String?
    ): Mono<WebEndpointResponse<out HealthComponent>> {
        val health = super.health(apiVersion, securityContext, showAll, *path)
    
        return health.doOnNext {
            if (it.body.status == UP) {
                logger.info("Health status: {}, {}", it.body.status, ObjectMapper().writeValueAsString(it.body))
            }
        }
    }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-30
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多