Created
August 4, 2020 12:47
-
-
Save kyrielia/9d729991bf5f1f1ac724d0e2dbe5ba7e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* An extension of the Spring Boot Actuator health indicator. Implementing this abstract class will give you both a | |
* health check on /health, as well as a Prometheus metric representing the health check on /metrics (1 for up, 0 for | |
* down). | |
* <p> | |
* Note: Spring health indicators only run when /health is called. | |
*/ | |
abstract class HealthIndicatorWithMetric implements HealthIndicator { | |
private Logger log = LoggerFactory.getLogger(HealthIndicatorWithMetric.class); | |
// Micrometer won't update a gauge metric unless you use an atomic number | |
private AtomicInteger healthy = new AtomicInteger(0); | |
private final String metricName; | |
public HealthIndicatorWithMetric(MeterRegistry meterRegistry, String metricName) { | |
this.metricName = metricName; | |
meterRegistry.gauge(metricName, List.of(), healthy); | |
} | |
@Override | |
public final Health health() { | |
try { | |
Health health = performHealthCheck(); | |
if (Status.UP.equals(health.getStatus())) { | |
healthy.set(1); | |
} else { | |
healthy.set(0); | |
} | |
return health; | |
} catch (Exception e) { | |
log.error(metricName + " health check threw unhandled error", e); | |
healthy.set(0); | |
return Health.down().withException(e).build(); | |
} | |
} | |
public abstract Health performHealthCheck(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment