Last active
November 7, 2017 08:40
-
-
Save maust/3166c8b4471f34ee57f1995c79a56c20 to your computer and use it in GitHub Desktop.
Work around for duplicate metrics when using Spring Boot, Actuator, Eurkeka and Prometheus
This file contains 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
import io.prometheus.client.Collector; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.boot.actuate.endpoint.PublicMetrics; | |
import org.springframework.boot.actuate.metrics.Metric; | |
import org.springframework.stereotype.Component; | |
import java.util.*; | |
/** | |
* <p>Spring boot metrics integration for Prometheus exporter.</p> | |
* | |
* <pre><code>{@literal @}Bean | |
* public SpringBootMetricsCollector springBootMetricsCollector(Collection{@literal <}PublicMetrics{@literal >} publicMetrics) { | |
* SpringBootMetricsCollector springBootMetricsCollector = new SpringBootMetricsCollector(publicMetrics); | |
* springBootMetricsCollector.register(); | |
* return springBootMetricsCollector; | |
* } | |
* </code></pre> | |
*/ | |
@Component | |
public class SpringBootMetricsCollector extends Collector { | |
private final Collection<PublicMetrics> publicMetrics; | |
@Autowired | |
public SpringBootMetricsCollector(Collection<PublicMetrics> publicMetrics) { | |
this.publicMetrics = publicMetrics; | |
} | |
@Override | |
public List<MetricFamilySamples> collect() { | |
Map<String, MetricFamilySamples> samples = new HashMap<>(); | |
for (PublicMetrics publicMetrics : this.publicMetrics) { | |
for (Metric<?> metric : publicMetrics.metrics()) { | |
String name = Collector.sanitizeMetricName(metric.getName()); | |
double value = metric.getValue().doubleValue(); | |
MetricFamilySamples metricFamilySamples = new MetricFamilySamples( | |
name, Type.GAUGE, name, Collections.singletonList( | |
new MetricFamilySamples.Sample(name, new ArrayList<String>(), new ArrayList<String>(), value))); | |
samples.put(name, metricFamilySamples); | |
} | |
} | |
return new ArrayList<>(samples.values()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment