forked from prometheus/client_rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom-metric.rs
More file actions
45 lines (37 loc) · 1.46 KB
/
custom-metric.rs
File metadata and controls
45 lines (37 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
use prometheus_client::encoding::{text::encode, EncodeMetric, MetricEncoder, NoLabelSet};
use prometheus_client::metrics::MetricType;
use prometheus_client::registry::Registry;
/// Showcasing encoding of custom metrics.
///
/// Related to the concept of "Custom Collectors" in other implementations.
///
/// [`MyCustomMetric`] generates and encodes a random number on each scrape.
#[derive(Debug)]
struct MyCustomMetric {}
impl EncodeMetric for MyCustomMetric {
fn encode(&self, mut encoder: MetricEncoder) -> Result<(), std::fmt::Error> {
// This method is called on each Prometheus server scrape. Allowing you
// to execute whatever logic is needed to generate and encode your
// custom metric.
//
// Do keep in mind that "with great power comes great responsibility".
// E.g. every CPU cycle spend in this method delays the response send to
// the Prometheus server.
encoder.encode_counter::<NoLabelSet, _, u64>(&rand::random::<u64>(), None)
}
fn metric_type(&self) -> prometheus_client::metrics::MetricType {
MetricType::Counter
}
}
fn main() {
let mut registry = Registry::default();
let metric = MyCustomMetric {};
registry.register(
"my_custom_metric",
"Custom metric returning a random number on each scrape",
metric,
);
let mut encoded = String::new();
encode(&mut encoded, ®istry).unwrap();
println!("Scrape output:\n{encoded:?}");
}