Skip to content

Commit 8068b8a

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 <me+cratelyn@katelyn.world>
1 parent 12923ca commit 8068b8a

1 file changed

Lines changed: 20 additions & 0 deletions

File tree

src/metrics/family.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,26 @@ impl<S: Clone + std::hash::Hash + Eq, M, C: MetricConstructor<M>> Family<S, M, C
288288
self.metrics.write().clear()
289289
}
290290

291+
/// Returns `true` if the given label set exists within the metric family.
292+
///
293+
/// ```
294+
/// # use prometheus_client::metrics::counter::{Atomic, Counter};
295+
/// # use prometheus_client::metrics::family::Family;
296+
/// #
297+
/// let family = Family::<Vec<(String, String)>, Counter>::default();
298+
/// let get = vec![("method".to_owned(), "GET".to_owned())];
299+
/// let post = vec![("method".to_owned(), "POST".to_owned())];
300+
///
301+
/// // Create the metric with labels `method="GET"`.
302+
/// family.get_or_create(&get).inc();
303+
///
304+
/// assert!(family.contains(&get), "a `method=\"GET\"`-labeled metric exists");
305+
/// assert!(!family.contains(&post), "a `method=\"POST\"`-labeled metric does NOT exist");
306+
/// ```
307+
pub fn contains(&self, label_set: &S) -> bool {
308+
self.metrics.read().get(label_set).is_some()
309+
}
310+
291311
pub(crate) fn read(&self) -> RwLockReadGuard<HashMap<S, M>> {
292312
self.metrics.read()
293313
}

0 commit comments

Comments
 (0)