Home > Back-end >  Report spring boot actuator health status as a metric
Report spring boot actuator health status as a metric

Time:11-09

I want to report the health status of the application as a gauge and I desired to use the same health indicators as spring-boot-actuator, however, I don't see any exportable components from the spring-boot-actuator dependency that I might be able to use here.

The code I would like to write:

@Component
public class HealthCounterMetric {
  private final Counter statusCounter;

  public HealthCounterMetric(MeterRegistry meterRegistry, SystemHealth systemHealth) {
    this.statusCounter = meterRegistry.counter("service.status");
  }

  @Scheduled(fixedRate = 30000L)
  public void reportHealth() {
    //do report health
  }
}

Of course, SystemHealth is not an exported bean. Does spring boot actuator export beans that I can consume this way?

CodePudding user response:

The reference documentation describes how to do this by mapping the HealthEndpoint's response to a gauge:

@Configuration(proxyBeanMethods = false)
public class MyHealthMetricsExportConfiguration {

    public MyHealthMetricsExportConfiguration(MeterRegistry registry, HealthEndpoint healthEndpoint) {
        // This example presumes common tags (such as the app) are applied elsewhere
        Gauge.builder("health", healthEndpoint, this::getStatusCode).strongReference(true).register(registry);
    }

    private int getStatusCode(HealthEndpoint health) {
        Status status = health.health().getStatus();
        if (Status.UP.equals(status)) {
            return 3;
        }
        if (Status.OUT_OF_SERVICE.equals(status)) {
            return 2;
        }
        if (Status.DOWN.equals(status)) {
            return 1;
        }
        return 0;
    }

}
  • Related