Skip to content

Commit

Permalink
feat(metrics/family): contains() checks if metrics exist
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
cratelyn committed Nov 18, 2024
1 parent 12923ca commit 8068b8a
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/metrics/family.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,26 @@ impl<S: Clone + std::hash::Hash + Eq, M, C: MetricConstructor<M>> Family<S, M, C
self.metrics.write().clear()
}

/// Returns `true` if the given label set exists within the metric family.
///
/// ```
/// # use prometheus_client::metrics::counter::{Atomic, Counter};
/// # use prometheus_client::metrics::family::Family;
/// #
/// let family = Family::<Vec<(String, String)>, Counter>::default();
/// let get = vec![("method".to_owned(), "GET".to_owned())];
/// let post = vec![("method".to_owned(), "POST".to_owned())];
///
/// // Create the metric with labels `method="GET"`.
/// family.get_or_create(&get).inc();
///
/// assert!(family.contains(&get), "a `method=\"GET\"`-labeled metric exists");
/// assert!(!family.contains(&post), "a `method=\"POST\"`-labeled metric does NOT exist");
/// ```
pub fn contains(&self, label_set: &S) -> bool {
self.metrics.read().get(label_set).is_some()
}

pub(crate) fn read(&self) -> RwLockReadGuard<HashMap<S, M>> {
self.metrics.read()
}
Expand Down

0 comments on commit 8068b8a

Please sign in to comment.