From 413f88940565d4fc4da6443894f9dae5904975ff Mon Sep 17 00:00:00 2001 From: Gregor Zeitlinger Date: Thu, 17 Oct 2024 15:29:19 +0200 Subject: [PATCH] Add clear() method into PrometheusRegistry to unregister all collectors (#1158) * Add clear() method into PrometheusRegistry to unregister all collectors Signed-off-by: Petr Holubec * format Signed-off-by: Gregor Zeitlinger * test Signed-off-by: Gregor Zeitlinger --------- Signed-off-by: Gregor Zeitlinger Co-authored-by: Petr Holubec --- .../metrics/model/registry/PrometheusRegistry.java | 6 ++++++ .../model/registry/PrometheusRegistryTest.java | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/registry/PrometheusRegistry.java b/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/registry/PrometheusRegistry.java index 026560bb9..5038da894 100644 --- a/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/registry/PrometheusRegistry.java +++ b/prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/registry/PrometheusRegistry.java @@ -56,6 +56,12 @@ public void unregister(MultiCollector collector) { } } + public void clear() { + collectors.clear(); + multiCollectors.clear(); + prometheusNames.clear(); + } + public MetricSnapshots scrape() { return scrape((PrometheusScrapeRequest) null); } diff --git a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/registry/PrometheusRegistryTest.java b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/registry/PrometheusRegistryTest.java index 6557c0ecf..e0f22a9dc 100644 --- a/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/registry/PrometheusRegistryTest.java +++ b/prometheus-metrics-model/src/test/java/io/prometheus/metrics/model/registry/PrometheusRegistryTest.java @@ -145,4 +145,16 @@ public void registerOkMultiCollector() { snapshots = registry.scrape(); assertThat(snapshots.size()).isZero(); } + + @Test + public void clearOk() { + PrometheusRegistry registry = new PrometheusRegistry(); + registry.register(counterA1); + registry.register(counterB); + registry.register(gaugeA); + assertThat(registry.scrape().size()).isEqualTo(3); + + registry.clear(); + assertThat(registry.scrape().size()).isZero(); + } }