forked from tikv/rust-prometheus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_hyper.rs
68 lines (56 loc) · 1.97 KB
/
example_hyper.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
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use hyper::{
header::CONTENT_TYPE,
service::{make_service_fn, service_fn},
Body, Request, Response, Server,
};
use prometheus::{Counter, Encoder, Gauge, HistogramVec, TextEncoder};
use lazy_static::lazy_static;
use prometheus::{labels, opts, register_counter, register_gauge, register_histogram_vec};
lazy_static! {
static ref HTTP_COUNTER: Counter = register_counter!(opts!(
"example_http_requests_total",
"Number of HTTP requests made.",
labels! {"handler" => "all",}
))
.unwrap();
static ref HTTP_BODY_GAUGE: Gauge = register_gauge!(opts!(
"example_http_response_size_bytes",
"The HTTP response sizes in bytes.",
labels! {"handler" => "all",}
))
.unwrap();
static ref HTTP_REQ_HISTOGRAM: HistogramVec = register_histogram_vec!(
"example_http_request_duration_seconds",
"The HTTP request latencies in seconds.",
&["handler"]
)
.unwrap();
}
async fn serve_req(_req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
let encoder = TextEncoder::new();
HTTP_COUNTER.inc();
let timer = HTTP_REQ_HISTOGRAM.with_label_values(&["all"]).start_timer();
let metric_families = prometheus::gather();
let mut buffer = vec![];
encoder.encode(&metric_families, &mut buffer).unwrap();
HTTP_BODY_GAUGE.set(buffer.len() as f64);
let response = Response::builder()
.status(200)
.header(CONTENT_TYPE, encoder.format_type())
.body(Body::from(buffer))
.unwrap();
timer.observe_duration();
Ok(response)
}
#[tokio::main]
async fn main() {
let addr = ([127, 0, 0, 1], 9898).into();
println!("Listening on https://{}", addr);
let serve_future = Server::bind(&addr).serve(make_service_fn(|_| async {
Ok::<_, hyper::Error>(service_fn(serve_req))
}));
if let Err(err) = serve_future.await {
eprintln!("server error: {}", err);
}
}