当前位置: 代码迷 >> java >> 启用登录 Spring Boot 执行器健康检查 API
  详细解决方案

启用登录 Spring Boot 执行器健康检查 API

热度:39   发布时间:2023-07-26 14:10:34.0

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

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

提到

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

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

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

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

更多关于执行器终点延伸,为4.8。 扩展现有端点

如果使用 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))
        }
    }
}

}

  相关解决方案