-
Notifications
You must be signed in to change notification settings - Fork 396
Expand file tree
/
Copy pathmetrics.rs
More file actions
54 lines (43 loc) · 1.68 KB
/
metrics.rs
File metadata and controls
54 lines (43 loc) · 1.68 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
46
47
48
49
50
51
52
53
54
use prometheus::{self, histogram_opts, register_histogram};
use warp::{reject::Rejection, reply::Reply, Filter};
#[derive(Clone, Debug)]
pub struct GatewayMetrics {
pub time_elapsed_db_post: prometheus::Histogram,
}
impl GatewayMetrics {
pub fn start(metrics_port: u16) -> anyhow::Result<Self> {
let registry = prometheus::Registry::new();
let time_elapsed_db_post = register_histogram!(histogram_opts!(
"time_elapsed_db_post",
"Time elapsed in DB posts"
))?;
registry.register(Box::new(time_elapsed_db_post.clone()))?;
let metrics_route = warp::path!("metrics")
.and(warp::any().map(move || registry.clone()))
.and_then(GatewayMetrics::metrics_handler);
tokio::task::spawn(async move {
warp::serve(metrics_route)
.run(([0, 0, 0, 0], metrics_port))
.await;
});
Ok(Self {
time_elapsed_db_post,
})
}
pub async fn metrics_handler(registry: prometheus::Registry) -> Result<impl Reply, Rejection> {
use prometheus::Encoder;
let encoder = prometheus::TextEncoder::new();
let mut buffer = Vec::new();
if let Err(e) = encoder.encode(®istry.gather(), &mut buffer) {
eprintln!("could not encode prometheus metrics: {e}");
};
let res = String::from_utf8(buffer.clone())
.inspect_err(|e| eprintln!("prometheus metrics could not be parsed correctly: {e}"))
.unwrap_or_default();
buffer.clear();
Ok(res)
}
pub fn register_db_response_time_post(&self, value: f64) {
self.time_elapsed_db_post.observe(value);
}
}