Skip to content

Instantly share code, notes, and snippets.

@nagypet
Created October 26, 2021 15:11
Show Gist options
  • Save nagypet/167e537d1cbc736644a88c5acbfc33b4 to your computer and use it in GitHub Desktop.
Save nagypet/167e537d1cbc736644a88c5acbfc33b4 to your computer and use it in GitHub Desktop.
MicrometerMetricsService
@Slf4j
public class MicrometerMetricsService {
private DualMetric metricValidTemplate;
// Not possible to convert to a local variable, it is not working!
private final RepositoryMetricProvider repositoryMetricProvider = new RepositoryMetricProvider();
private final List<HealthIndicator> healthIndicators;
public MicrometerMetricsService(MeterRegistry registry, HealthContributorRegistry healthContributorRegistry) {
final String METRIC_HEALTH = Constants.SUBSYSTEM_NAME.toLowerCase() + ".health";
final String RESOURCE_COUNT_METRIC = Constants.SUBSYSTEM_NAME.toLowerCase() + ".resourcecount";
final String TEMPLATE_COUNT_METRIC = Constants.SUBSYSTEM_NAME.toLowerCase() + ".templatecount";
this.metricValidTemplate = new DualMetric(registry, Constants.SUBSYSTEM_NAME.toLowerCase(), "validtemplate");
// Health indicators
this.healthIndicators = healthContributorRegistry.stream() //
.map(c -> this.getIndicatorFromContributor(c)) //
.collect(Collectors.toList());
Gauge.builder(METRIC_HEALTH, healthIndicators, MicrometerMetricsService::healthToCode) //
.description("The current value of the composite health endpoint").register(registry);
// Count of resources
Gauge.builder(RESOURCE_COUNT_METRIC, this.repositoryMetricProvider, RepositoryMetricProvider::getResourceCountMetric)
.description("The current count of resources").baseUnit("pcs").register(registry);
// Count of templates
Gauge.builder(TEMPLATE_COUNT_METRIC, this.repositoryMetricProvider, RepositoryMetricProvider::getResourceCountMetric)
.description("The current count of templates").baseUnit("pcs").register(registry);
}
private HealthIndicator getIndicatorFromContributor(NamedContributor<HealthContributor> namedContributor) {
log.debug(String.format("Using health contributor: '%s'", namedContributor.getName()));
HealthContributor contributor = namedContributor.getContributor();
if (contributor instanceof HealthIndicator) {
return (HealthIndicator) contributor;
}
if (contributor instanceof CompositeHealthContributor) {
CompositeHealthContributor compositeHealthContributor = (CompositeHealthContributor) contributor;
for (NamedContributor<HealthContributor> elementOfComposite : compositeHealthContributor) {
return getIndicatorFromContributor(elementOfComposite);
}
}
throw new UnexpectedConditionException();
}
private static int healthToCode(List<HealthIndicator> indicators) {
for (HealthIndicator indicator : indicators) {
Status status = indicator.health().getStatus();
if (Status.DOWN.equals(status)) {
return 0;
}
}
return 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment