forked from tikv/rust-prometheus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_custom_registry.rs
73 lines (60 loc) · 2.49 KB
/
example_custom_registry.rs
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Copyright 2019 - rust-prometheus authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
//! This examples shows how to use multiple and custom registries,
//! and how to perform registration across function boundaries.
#[macro_use]
extern crate lazy_static;
extern crate prometheus;
use std::collections::HashMap;
use prometheus::{Encoder, IntCounter, Registry};
lazy_static! {
static ref DEFAULT_COUNTER: IntCounter = IntCounter::new("default", "generic counter").unwrap();
static ref CUSTOM_COUNTER: IntCounter = IntCounter::new("custom", "dedicated counter").unwrap();
}
fn main() {
// Register default metrics.
default_metrics(prometheus::default_registry());
// Register custom metrics to a custom registry.
let mut labels = HashMap::new();
labels.insert("mykey".to_string(), "myvalue".to_string());
let custom_registry = Registry::new_custom(Some("myprefix".to_string()), Some(labels)).unwrap();
custom_metrics(&custom_registry);
// Print metrics for the default registry.
let mut buffer = Vec::<u8>::new();
let encoder = prometheus::TextEncoder::new();
encoder.encode(&prometheus::gather(), &mut buffer).unwrap();
println!("## Default registry");
println!("{}", String::from_utf8(buffer.clone()).unwrap());
// Print metrics for the custom registry.
let mut buffer = Vec::<u8>::new();
let encoder = prometheus::TextEncoder::new();
encoder
.encode(&custom_registry.gather(), &mut buffer)
.unwrap();
println!("## Custom registry");
println!("{}", String::from_utf8(buffer.clone()).unwrap());
}
/// Default metrics, to be collected by the default registry.
fn default_metrics(registry: &Registry) {
registry
.register(Box::new(DEFAULT_COUNTER.clone()))
.unwrap();
DEFAULT_COUNTER.inc();
assert_eq!(DEFAULT_COUNTER.get(), 1);
}
/// Custom metrics, to be collected by a dedicated registry.
fn custom_metrics(registry: &Registry) {
registry.register(Box::new(CUSTOM_COUNTER.clone())).unwrap();
CUSTOM_COUNTER.inc_by(42);
assert_eq!(CUSTOM_COUNTER.get(), 42);
}