Start second server on different port for metrics endpoint (#1444)

* Start second server on different port for metrics endpoint

* Don't track metrics on metrics server
This commit is contained in:
Valentin Brandl 2022-10-08 01:28:32 +02:00 committed by GitHub
parent a7d8954178
commit ee0b71a4ac
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -23,6 +23,46 @@ use std::{
};
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()
@ -33,25 +73,10 @@ async fn main() {
.with(tracing_subscriber::fmt::layer())
.init();
let recorder_handle = setup_metrics_recorder();
let app = Router::new()
.route("/fast", get(|| async {}))
.route(
"/slow",
get(|| async {
tokio::time::sleep(Duration::from_secs(1)).await;
}),
)
.route("/metrics", get(move || ready(recorder_handle.render())))
.route_layer(middleware::from_fn(track_metrics));
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();
// 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 {