Skip to content

Commit

Permalink
Fix #146: Add with_prefix_and_labels constructor to Registry
Browse files Browse the repository at this point in the history
Signed-off-by: Adrian Pop <popadrian1996@gmail.com>
  • Loading branch information
popadi committed May 29, 2023
1 parent d001ba0 commit 4d99f9d
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions src/registry.rs
Expand Up @@ -75,6 +75,18 @@ impl Registry {
}
}

/// Creates a new default [`Registry`] with the given prefix and labels.
pub fn with_prefix_and_labels(
prefix: impl Into<String>,
labels: impl Iterator<Item = (Cow<'static, str>, Cow<'static, str>)>,
) -> Self {
Self {
prefix: Some(Prefix(prefix.into())),
labels: labels.into_iter().collect(),
..Default::default()
}
}

/// Register a metric with the [`Registry`].
///
/// Note: In the Open Metrics text exposition format some metric types have
Expand Down Expand Up @@ -518,6 +530,40 @@ mod tests {
use super::*;
use crate::metrics::counter::Counter;

#[test]
fn constructors() {
let prefix = "test_prefix";
let counter_name = "test_counter";

let mut registry = Registry::with_prefix(prefix);
let counter: Counter = Counter::default();
registry.register(counter_name, "some help", counter);

assert_eq!(
Some((prefix.to_string() + "_" + counter_name, vec![])),
registry
.iter_metrics()
.map(|(desc, _)| (desc.name.clone(), desc.labels.clone()))
.next()
);

let labels = vec![
(Cow::Borrowed("global_label_1"), Cow::Borrowed("value_1")),
(Cow::Borrowed("global_label_1"), Cow::Borrowed("value_2")),
];
let mut registry = Registry::with_prefix_and_labels(prefix, labels.clone().into_iter());
let counter: Counter = Counter::default();
registry.register(counter_name, "some help", counter);

assert_eq!(
Some((prefix.to_string() + "_" + counter_name, labels)),
registry
.iter_metrics()
.map(|(desc, _)| (desc.name.clone(), desc.labels.clone()))
.next()
);
}

#[test]
fn register_and_iterate() {
let mut registry = Registry::default();
Expand Down

0 comments on commit 4d99f9d

Please sign in to comment.