prometheus_client/registry.rs
1//! Metric registry implementation.
2//!
3//! See [`Registry`] for details.
4
5use std::borrow::Cow;
6
7use crate::collector::Collector;
8use crate::encoding::{DescriptorEncoder, EncodeMetric};
9use crate::metrics::MetricType;
10
11/// A metric registry.
12///
13/// First off one registers metrics with the registry via
14/// [`Registry::register`]. Later on the [`Registry`] is passed to an encoder
15/// collecting samples of each metric by iterating all metrics in the
16/// [`Registry`].
17///
18/// [`Registry`] is the core building block, generic over the metric type being
19/// registered. Out of convenience, the generic type parameter is set to use
20/// dynamic dispatching by default to be able to register different types of
21/// metrics (e.g. [`Counter`](crate::metrics::counter::Counter) and
22/// [`Gauge`](crate::metrics::gauge::Gauge)) with the same registry. Advanced
23/// users might want to use their custom types.
24///
25/// ```
26/// # use prometheus_client::encoding::text::encode;
27/// # use prometheus_client::metrics::counter::{Atomic as _, Counter};
28/// # use prometheus_client::metrics::gauge::{Atomic as _, Gauge};
29/// # use prometheus_client::registry::Registry;
30/// #
31/// // Create a metric registry.
32/// let mut registry = Registry::default();
33///
34/// let counter: Counter = Counter::default();
35/// let gauge: Gauge = Gauge::default();
36///
37/// registry.register(
38/// "my_counter",
39/// "This is my counter",
40/// counter.clone(),
41/// );
42/// registry.register(
43/// "my_gauge",
44/// "This is my gauge",
45/// gauge.clone(),
46/// );
47///
48/// # // Encode all metrics in the registry in the text format.
49/// # let mut buffer = String::new();
50/// # encode(&mut buffer, ®istry).unwrap();
51/// #
52/// # let expected = "# HELP my_counter This is my counter.\n".to_owned() +
53/// # "# TYPE my_counter counter\n" +
54/// # "my_counter_total 0\n" +
55/// # "# HELP my_gauge This is my gauge.\n" +
56/// # "# TYPE my_gauge gauge\n" +
57/// # "my_gauge 0\n" +
58/// # "# EOF\n";
59/// # assert_eq!(expected, buffer);
60/// ```
61#[derive(Debug, Default)]
62pub struct Registry {
63 prefix: Option<Prefix>,
64 labels: Vec<(Cow<'static, str>, Cow<'static, str>)>,
65 metrics: Vec<(Descriptor, Box<dyn Metric>)>,
66 collectors: Vec<Box<dyn Collector>>,
67 sub_registries: Vec<Registry>,
68}
69
70impl Registry {
71 /// Creates a new default [`Registry`] with the given prefix.
72 pub fn with_prefix(prefix: impl Into<String>) -> Self {
73 Self {
74 prefix: Some(Prefix(prefix.into())),
75 ..Default::default()
76 }
77 }
78
79 /// Creates a new default [`Registry`] with the given labels.
80 pub fn with_labels(
81 labels: impl Iterator<Item = (Cow<'static, str>, Cow<'static, str>)>,
82 ) -> Self {
83 Self {
84 labels: labels.into_iter().collect(),
85 ..Default::default()
86 }
87 }
88
89 /// Creates a new default [`Registry`] with the given prefix and labels.
90 pub fn with_prefix_and_labels(
91 prefix: impl Into<String>,
92 labels: impl Iterator<Item = (Cow<'static, str>, Cow<'static, str>)>,
93 ) -> Self {
94 Self {
95 prefix: Some(Prefix(prefix.into())),
96 labels: labels.into_iter().collect(),
97 ..Default::default()
98 }
99 }
100
101 /// Register a metric with the [`Registry`].
102 ///
103 /// Note: In the Open Metrics text exposition format some metric types have
104 /// a special suffix, e.g. the
105 /// [`Counter`](crate::metrics::counter::Counter`) metric with `_total`.
106 /// These suffixes are inferred through the metric type and must not be
107 /// appended to the metric name manually by the user.
108 ///
109 /// Note: A full stop punctuation mark (`.`) is automatically added to the
110 /// passed help text.
111 ///
112 /// Use [`Registry::register_with_unit`] whenever a unit for the given
113 /// metric is known.
114 ///
115 /// ```
116 /// # use prometheus_client::metrics::counter::{Atomic as _, Counter};
117 /// # use prometheus_client::registry::{Registry, Unit};
118 /// #
119 /// let mut registry = Registry::default();
120 /// let counter: Counter = Counter::default();
121 ///
122 /// registry.register("my_counter", "This is my counter", counter.clone());
123 /// ```
124 #[track_caller]
125 pub fn register<N: Into<String>, H: Into<String>>(
126 &mut self,
127 name: N,
128 help: H,
129 metric: impl Metric,
130 ) {
131 self.priv_register(name, help, metric, None)
132 }
133
134 /// Register a metric with the [`Registry`] specifying the metric's unit.
135 ///
136 /// See [`Registry::register`] for additional documentation.
137 ///
138 /// Note: In the Open Metrics text exposition format units are appended to
139 /// the metric name. This is done automatically. Users must not append the
140 /// unit to the name manually.
141 ///
142 /// ```
143 /// # use prometheus_client::metrics::counter::{Atomic as _, Counter};
144 /// # use prometheus_client::registry::{Registry, Unit};
145 /// #
146 /// let mut registry = Registry::default();
147 /// let counter: Counter = Counter::default();
148 ///
149 /// registry.register_with_unit(
150 /// "my_counter",
151 /// "This is my counter",
152 /// Unit::Seconds,
153 /// counter.clone(),
154 /// );
155 /// ```
156 #[track_caller]
157 pub fn register_with_unit<N: Into<String>, H: Into<String>>(
158 &mut self,
159 name: N,
160 help: H,
161 unit: Unit,
162 metric: impl Metric,
163 ) {
164 self.priv_register(name, help, metric, Some(unit))
165 }
166
167 #[track_caller]
168 fn priv_register<N: Into<String>, H: Into<String>>(
169 &mut self,
170 name: N,
171 help: H,
172 metric: impl Metric,
173 unit: Option<Unit>,
174 ) {
175 let descriptor = Descriptor::new(name, help, unit);
176 debug_assert!(
177 metric.metric_type() != MetricType::Counter || !descriptor.name.ends_with("_total"),
178 "counter name {} must not end with _total, the suffix is added during encoding",
179 descriptor.name
180 );
181 self.metrics.push((descriptor, Box::new(metric)));
182 }
183
184 /// Register a [`Collector`].
185 ///
186 /// ```
187 /// # use prometheus_client::metrics::counter::ConstCounter;
188 /// # use prometheus_client::registry::Registry;
189 /// # use prometheus_client::collector::Collector;
190 /// # use prometheus_client::encoding::{DescriptorEncoder, EncodeMetric};
191 /// #
192 /// #[derive(Debug)]
193 /// struct MyCollector {}
194 ///
195 /// impl Collector for MyCollector {
196 /// fn encode(&self, mut encoder: DescriptorEncoder) -> Result<(), std::fmt::Error> {
197 /// let counter = ConstCounter::new(42u64);
198 /// let metric_encoder = encoder.encode_descriptor(
199 /// "my_counter",
200 /// "some help",
201 /// None,
202 /// counter.metric_type(),
203 /// )?;
204 /// counter.encode(metric_encoder)?;
205 /// Ok(())
206 /// }
207 /// }
208 ///
209 /// let my_collector = Box::new(MyCollector{});
210 ///
211 /// let mut registry = Registry::default();
212 ///
213 /// registry.register_collector(my_collector);
214 /// ```
215 pub fn register_collector(&mut self, collector: Box<dyn Collector>) {
216 self.collectors.push(collector);
217 }
218
219 /// Create a sub-registry to register metrics with a common prefix.
220 ///
221 /// Say you would like to prefix one set of metrics with `subsystem_a` and
222 /// one set of metrics with `subsystem_b`. Instead of prefixing each metric
223 /// with the corresponding subsystem string individually, you can create two
224 /// sub-registries like demonstrated below.
225 ///
226 /// This can be used to pass a prefixed sub-registry down to a subsystem of
227 /// your architecture automatically adding a prefix to each metric the
228 /// subsystem registers.
229 ///
230 /// ```
231 /// # use prometheus_client::metrics::counter::{Atomic as _, Counter};
232 /// # use prometheus_client::registry::{Registry, Unit};
233 /// #
234 /// let mut registry = Registry::default();
235 ///
236 /// let subsystem_a_counter_1: Counter = Counter::default();
237 /// let subsystem_a_counter_2: Counter = Counter::default();
238 ///
239 /// let subsystem_a_registry = registry.sub_registry_with_prefix("subsystem_a");
240 /// subsystem_a_registry.register("counter_1", "", subsystem_a_counter_1.clone());
241 /// subsystem_a_registry.register("counter_2", "", subsystem_a_counter_2.clone());
242 ///
243 /// let subsystem_b_counter_1: Counter = Counter::default();
244 /// let subsystem_b_counter_2: Counter = Counter::default();
245 ///
246 /// let subsystem_b_registry = registry.sub_registry_with_prefix("subsystem_b");
247 /// subsystem_b_registry.register("counter_1", "", subsystem_b_counter_1.clone());
248 /// subsystem_b_registry.register("counter_2", "", subsystem_b_counter_2.clone());
249 /// ```
250 ///
251 /// See [`Registry::sub_registry_with_label`] for the same functionality,
252 /// but namespacing with a label instead of a metric name prefix.
253 pub fn sub_registry_with_prefix<P: AsRef<str>>(&mut self, prefix: P) -> &mut Self {
254 let sub_registry = Registry {
255 prefix: Some(Prefix(
256 self.prefix.clone().map(|p| p.0 + "_").unwrap_or_default() + prefix.as_ref(),
257 )),
258 labels: self.labels.clone(),
259 ..Default::default()
260 };
261
262 self.priv_sub_registry(sub_registry)
263 }
264
265 /// Like [`Registry::sub_registry_with_prefix`] but with a label instead.
266 pub fn sub_registry_with_label(
267 &mut self,
268 label: (Cow<'static, str>, Cow<'static, str>),
269 ) -> &mut Self {
270 self.sub_registry_with_labels(std::iter::once(label))
271 }
272
273 /// Like [`Registry::sub_registry_with_prefix`] but with multiple labels instead.
274 pub fn sub_registry_with_labels(
275 &mut self,
276 labels: impl Iterator<Item = (Cow<'static, str>, Cow<'static, str>)>,
277 ) -> &mut Self {
278 let mut new_labels = self.labels.clone();
279 new_labels.extend(labels);
280
281 let sub_registry = Registry {
282 prefix: self.prefix.clone(),
283 labels: new_labels,
284 ..Default::default()
285 };
286
287 self.priv_sub_registry(sub_registry)
288 }
289
290 fn priv_sub_registry(&mut self, sub_registry: Self) -> &mut Self {
291 self.sub_registries.push(sub_registry);
292
293 self.sub_registries
294 .last_mut()
295 .expect("sub_registries not to be empty.")
296 }
297
298 pub(crate) fn encode(&self, encoder: &mut DescriptorEncoder) -> Result<(), std::fmt::Error> {
299 for (descriptor, metric) in self.metrics.iter().filter(|(_, m)| !m.is_empty()) {
300 let mut descriptor_encoder =
301 encoder.with_prefix_and_labels(self.prefix.as_ref(), &self.labels);
302 let metric_encoder = descriptor_encoder.encode_descriptor(
303 &descriptor.name,
304 &descriptor.help,
305 descriptor.unit.as_ref(),
306 EncodeMetric::metric_type(metric.as_ref()),
307 )?;
308 metric.encode(metric_encoder)?;
309 }
310
311 for collector in self.collectors.iter() {
312 let descriptor_encoder =
313 encoder.with_prefix_and_labels(self.prefix.as_ref(), &self.labels);
314 collector.encode(descriptor_encoder)?;
315 }
316
317 for registry in self.sub_registries.iter() {
318 registry.encode(encoder)?;
319 }
320
321 Ok(())
322 }
323}
324
325/// Metric prefix
326#[derive(Clone, Debug)]
327pub(crate) struct Prefix(String);
328
329impl Prefix {
330 pub(crate) fn as_str(&self) -> &str {
331 self.0.as_str()
332 }
333}
334
335impl From<String> for Prefix {
336 fn from(s: String) -> Self {
337 Prefix(s)
338 }
339}
340
341/// OpenMetrics metric descriptor.
342#[derive(Debug, Clone)]
343struct Descriptor {
344 name: String,
345 help: String,
346 unit: Option<Unit>,
347}
348
349impl Descriptor {
350 /// Create new [`Descriptor`].
351 fn new<N: Into<String>, H: Into<String>>(name: N, help: H, unit: Option<Unit>) -> Self {
352 Self {
353 name: name.into(),
354 help: help.into() + ".",
355 unit,
356 }
357 }
358}
359
360/// Metric units recommended by Open Metrics.
361///
362/// See [`Unit::Other`] to specify alternative units.
363#[derive(Debug, Clone, PartialEq, Eq, Hash)]
364#[allow(missing_docs)]
365pub enum Unit {
366 Amperes,
367 Bytes,
368 Celsius,
369 Grams,
370 Joules,
371 Meters,
372 Ratios,
373 Seconds,
374 Volts,
375 Other(String),
376}
377
378impl Unit {
379 /// Returns the given Unit's str representation.
380 pub fn as_str(&self) -> &str {
381 match self {
382 Unit::Amperes => "amperes",
383 Unit::Bytes => "bytes",
384 Unit::Celsius => "celsius",
385 Unit::Grams => "grams",
386 Unit::Joules => "joules",
387 Unit::Meters => "meters",
388 Unit::Ratios => "ratios",
389 Unit::Seconds => "seconds",
390 Unit::Volts => "volts",
391 Unit::Other(other) => other.as_str(),
392 }
393 }
394}
395
396/// Super trait representing an abstract Prometheus metric.
397pub trait Metric: crate::encoding::EncodeMetric + Send + Sync + std::fmt::Debug + 'static {}
398
399impl<T> Metric for T where T: crate::encoding::EncodeMetric + Send + Sync + std::fmt::Debug + 'static
400{}
401
402#[cfg(test)]
403mod tests {
404 use super::*;
405 use crate::metrics::{counter::Counter, gauge::Gauge};
406
407 #[test]
408 #[cfg_attr(debug_assertions, should_panic(expected = "must not end with _total"))]
409 fn register_counter_with_total_suffix() {
410 let counter: Counter = Counter::default();
411 Registry::default().register("my_counter_total", "", counter);
412 }
413
414 #[test]
415 fn register_gauge_with_total_suffix() {
416 let gauge: Gauge = Gauge::default();
417 Registry::default().register("my_gauge_total", "", gauge);
418 }
419}