-
Notifications
You must be signed in to change notification settings - Fork 967
/
main.rs
121 lines (104 loc) · 3.42 KB
/
main.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
//! Someday tower-http will hopefully have a metrics middleware, until then you can track
//! metrics like this.
//!
//! Run with
//!
//! ```not_rust
//! cd examples && cargo run -p example-prometheus-metrics
//! ```
use axum::{
extract::MatchedPath,
http::Request,
middleware::{self, Next},
response::IntoResponse,
routing::get,
Router,
};
use metrics_exporter_prometheus::{Matcher, PrometheusBuilder, PrometheusHandle};
use std::{
future::ready,
net::SocketAddr,
time::{Duration, Instant},
};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
fn metrics_app() -> Router {
let recorder_handle = setup_metrics_recorder();
Router::new().route("/metrics", get(move || ready(recorder_handle.render())))
}
fn main_app() -> Router {
Router::new()
.route("/fast", get(|| async {}))
.route(
"/slow",
get(|| async {
tokio::time::sleep(Duration::from_secs(1)).await;
}),
)
.route_layer(middleware::from_fn(track_metrics))
}
async fn start_main_server() {
let app = main_app();
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap()
}
async fn start_metrics_server() {
let app = metrics_app();
// NOTE: expose metrics enpoint on a different port
let addr = SocketAddr::from(([127, 0, 0, 1], 3001));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap()
}
#[tokio::main]
async fn main() {
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "example_todos=debug,tower_http=debug".into()),
)
.with(tracing_subscriber::fmt::layer())
.init();
// The `/metrics` endpoint should not be publicly available. If behind a reverse proxy, this
// can be achieved by rejecting requests to `/metrics`. In this example, a second server is
// started on another port to expose `/metrics`.
let (_main_server, _metrics_server) = tokio::join!(start_main_server(), start_metrics_server());
}
fn setup_metrics_recorder() -> PrometheusHandle {
const EXPONENTIAL_SECONDS: &[f64] = &[
0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0,
];
PrometheusBuilder::new()
.set_buckets_for_metric(
Matcher::Full("http_requests_duration_seconds".to_string()),
EXPONENTIAL_SECONDS,
)
.unwrap()
.install_recorder()
.unwrap()
}
async fn track_metrics<B>(req: Request<B>, next: Next<B>) -> impl IntoResponse {
let start = Instant::now();
let path = if let Some(matched_path) = req.extensions().get::<MatchedPath>() {
matched_path.as_str().to_owned()
} else {
req.uri().path().to_owned()
};
let method = req.method().clone();
let response = next.run(req).await;
let latency = start.elapsed().as_secs_f64();
let status = response.status().as_u16().to_string();
let labels = [
("method", method.to_string()),
("path", path),
("status", status),
];
metrics::increment_counter!("http_requests_total", &labels);
metrics::histogram!("http_requests_duration_seconds", latency, &labels);
response
}