Skip to content

Commit 1b86b83

Browse files
committed
Add removeIf method to Meters
1 parent 8f75de4 commit 1b86b83

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

prometheus-metrics-core/src/main/java/io/prometheus/metrics/core/metrics/StatefulMetric.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import io.prometheus.metrics.model.snapshots.MetricSnapshot;
1111
import java.util.ArrayList;
1212
import java.util.Arrays;
13+
import java.util.Collections;
1314
import java.util.List;
1415
import java.util.Map;
1516
import java.util.concurrent.ConcurrentHashMap;
@@ -136,6 +137,11 @@ public void remove(String... labelValues) {
136137
data.remove(Arrays.asList(labelValues));
137138
}
138139

140+
/** Remove the data points when the given function. */
141+
public void removeIf(Function<List<String>, Boolean> f) {
142+
data.entrySet().removeIf(entry -> f.apply(Collections.unmodifiableList(entry.getKey())));
143+
}
144+
139145
/** Reset the metric (remove all data points). */
140146
public void clear() {
141147
data.clear();

prometheus-metrics-core/src/test/java/io/prometheus/metrics/core/metrics/StatefulMetricTest.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
55

66
import java.lang.reflect.Field;
7+
import java.util.Arrays;
8+
import java.util.List;
79
import java.util.Map;
810
import org.junit.jupiter.api.Test;
911

@@ -35,6 +37,28 @@ public void testLabelRemoveWhileCollecting() throws Exception {
3537
}
3638
}
3739

40+
@Test
41+
@SuppressWarnings("unchecked")
42+
public void testLabelRemoveIf() throws Exception {
43+
Counter counter = Counter.builder().name("testLabelRemoveIf").labelNames("label1", "label2").build();
44+
Field data = counter.getClass().getSuperclass().getDeclaredField("data");
45+
data.setAccessible(true);
46+
47+
counter.labelValues("a", "b").inc(1.0);
48+
counter.labelValues("a", "c").inc(3.0);
49+
counter.labelValues("a", "d").inc(7.0);
50+
counter.labelValues("e", "f").inc(8.0);
51+
52+
counter.removeIf(labels -> labels.size() == 2 && labels.get(0).equals("a"));
53+
54+
Map<List<String>, Counter.DataPoint> dataPoints =
55+
(Map<List<String>, Counter.DataPoint>) data.get(counter);
56+
57+
assertThat(dataPoints).hasSize(1);
58+
assertThat(dataPoints.get(Arrays.asList("e", "f"))).isNotNull();
59+
assertThat(dataPoints.get(Arrays.asList("e", "f")).get()).isEqualTo(8.0D);
60+
}
61+
3862
@Test
3963
public void testClear() {
4064
Counter counter = Counter.builder().name("test").labelNames("label1", "label2").build();

0 commit comments

Comments
 (0)