Skip to content

Commit 4218100

Browse files
committed
feat(metrics/family): len() returns the number of metrics
this commit introduces a `len()` method to `Family<S, M, C>`, which returns the number of series within a metric family. see also #245, which allows callers to check if a family `contains()` a given label set. ```shell $ cargo clippy --all-features --all-targets --tests Compiling prometheus-client v0.23.0 (/path/to/prometheus-client) warning: struct `Family` has a public `len` method, but no `is_empty` method --> src/metrics/family.rs:309:5 | 309 | pub fn len(&self) -> usize { | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#len_without_is_empty = note: `#[warn(clippy::len_without_is_empty)]` on by default warning: `prometheus-client` (lib) generated 1 warning warning: `prometheus-client` (lib test) generated 1 warning (1 duplicate) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.63s ``` Signed-off-by: katelyn martin <git@katelyn.world>
1 parent 77a034b commit 4218100

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

src/metrics/family.rs

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

344+
/// Returns the number of metrics in this 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+
/// assert_eq!(family.len(), 0);
352+
///
353+
/// // Will create the metric with label `method="GET"` on first call and
354+
/// // return a reference.
355+
/// family.get_or_create(&vec![("method".to_owned(), "GET".to_owned())]).inc();
356+
/// assert_eq!(family.len(), 1);
357+
///
358+
/// // Clear the family of all label sets.
359+
/// family.clear();
360+
/// assert_eq!(family.len(), 0);
361+
/// ```
362+
#[cfg(any(test, feature = "test-util"))]
363+
pub fn len(&self) -> usize {
364+
self.metrics.read().len()
365+
}
366+
367+
/// Returns `true` if the family contains no metrics.
368+
#[cfg(any(test, feature = "test-util"))]
369+
pub fn is_empty(&self) -> bool {
370+
self.metrics.read().is_empty()
371+
}
372+
344373
pub(crate) fn read(&self) -> RwLockReadGuard<'_, HashMap<S, M>> {
345374
self.metrics.read()
346375
}

0 commit comments

Comments
 (0)