Skip to content

Commit ac53ac1

Browse files
committed
feat(metrics/family): contains() checks if metrics exist
this commit introduces a small accessor to the `Family<S, M, C>` metric family type. this new `contains()` method allows callers to check whether or not a metric with the provided set of labels exists. if no metric has been created via e.g. `get_or_create()`, this method will return `false`. Signed-off-by: katelyn martin <git@katelyn.world>
1 parent 77a034b commit ac53ac1

1 file changed

Lines changed: 21 additions & 0 deletions

File tree

src/metrics/family.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,27 @@ impl<S: Clone + std::hash::Hash + Eq, M, C: MetricConstructor<M>> Family<S, M, C
341341
self.metrics.write().clear()
342342
}
343343

344+
/// Returns `true` if the given label set exists within the metric family.
345+
///
346+
/// ```
347+
/// # use prometheus_client::metrics::counter::{Atomic, Counter};
348+
/// # use prometheus_client::metrics::family::Family;
349+
/// #
350+
/// let family = Family::<Vec<(String, String)>, Counter>::default();
351+
/// let get = vec![("method".to_owned(), "GET".to_owned())];
352+
/// let post = vec![("method".to_owned(), "POST".to_owned())];
353+
///
354+
/// // Create the metric with labels `method="GET"`.
355+
/// family.get_or_create(&get).inc();
356+
///
357+
/// assert!(family.contains(&get), "a `method=\"GET\"`-labeled metric exists");
358+
/// assert!(!family.contains(&post), "a `method=\"POST\"`-labeled metric does NOT exist");
359+
/// ```
360+
#[cfg(any(test, feature = "test-util"))]
361+
pub fn contains(&self, label_set: &S) -> bool {
362+
self.metrics.read().get(label_set).is_some()
363+
}
364+
344365
pub(crate) fn read(&self) -> RwLockReadGuard<'_, HashMap<S, M>> {
345366
self.metrics.read()
346367
}

0 commit comments

Comments
 (0)