From 676ff5a1631ce4548c7f19cd7d80abb432a67382 Mon Sep 17 00:00:00 2001 From: Jon Schneider Date: Tue, 16 May 2017 12:03:04 -0500 Subject: [PATCH] Add temporary reflection hack to get meters into Prometheus CollectorRegistry (fixes #6) --- .../prometheus/PrometheusMeterRegistry.java | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/springframework/metrics/instrument/prometheus/PrometheusMeterRegistry.java b/src/main/java/org/springframework/metrics/instrument/prometheus/PrometheusMeterRegistry.java index 01a16607b5..62a7f9f160 100644 --- a/src/main/java/org/springframework/metrics/instrument/prometheus/PrometheusMeterRegistry.java +++ b/src/main/java/org/springframework/metrics/instrument/prometheus/PrometheusMeterRegistry.java @@ -15,15 +15,16 @@ */ package org.springframework.metrics.instrument.prometheus; -import io.prometheus.client.CollectorRegistry; +import io.prometheus.client.*; import io.prometheus.client.Gauge; -import io.prometheus.client.SimpleCollector; -import io.prometheus.client.Summary; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.metrics.instrument.*; +import org.springframework.metrics.instrument.Counter; import org.springframework.metrics.instrument.internal.AbstractMeterRegistry; import java.lang.ref.WeakReference; +import java.lang.reflect.Field; +import java.util.Map; import java.util.function.ToDoubleFunction; import java.util.function.UnaryOperator; import java.util.stream.Collectors; @@ -100,6 +101,21 @@ private , C extends SimpleCollector, collector = collectorTransform.apply(collector); + // since we don't yet create Histograms, the full name will be one of the metrics registered + // with the collector registry + // FIXME we should expose a getter on namesToCollectors in CollectorRegistry + try { + Field namesToCollectorsField = registry.getClass().getDeclaredField("namesToCollectors"); + namesToCollectorsField.setAccessible(true); + @SuppressWarnings("unchecked") Map namesToCollectors = + (Map) namesToCollectorsField.get(registry); + if(!namesToCollectors.containsKey(name)) { + registry.register(collector); + } + } catch (NoSuchFieldException | IllegalAccessException e) { + throw new RuntimeException(e); + } + return collector.labels(StreamSupport.stream(tags.spliterator(), false) .map(Tag::getValue) .collect(Collectors.toList())