Exporting Prometheus metrics with Axum

Ellie Huxtable

使用 Axum 匯出 Prometheus 指標

原文由 Ellie Huxtable 發布,訂閱此部落格

可觀測性很重要!在 Rust 中,我通常都用 Axum 作為 HTTP 框架,因為它用起來很順手、速度又快。

tower-http 提供了許多在不少專案中都會用到的實用 HTTP 中介層。目前它還沒有提供 metrics 中介層,不過未來也許會有!

Issue 追蹤連結

有不少 crate 會自動幫你把這些都處理好,但 Axum 範例 建議使用 metrics。老實說,我不需要什麼太複雜的東西,大多數時候我只想要一個帶有計數器等的 /metrics 端點就好——所以就選 metrics 了!

總之,首先我們需要設定 Prometheus exporter。這基本上就是用來產生 /metrics 內容的東西。它使用 metrics-exporter-prometheus 這個 crate。只有在可執行檔中才需要設定全域的 recorder——如果是函式庫的話,就交給使用者自己決定就好。

上面這段基本上就是我從前面提到的 Axum 範例直接搬過來的 😇

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()
}

我今天其實會設定兩個指標,但只有 history_requests_duration_seconds 需要額外設定。這是因為它是 histogram,我們需要告訴 exporter 要如何對資料進行分桶。

完成之後,我們就可以來寫 Axum 的中介層了!(從範例搬過來,並修改成可以正常編譯的版本。我會去開個 PR)

/// Middleware to record some common HTTP metrics
/// Generic over B to allow for arbitrary body types (eg Vec<u8>, Streams, a deserialized thing, etc)
/// Someday tower-http might provide a metrics middleware: https://github.com/tower-rs/tower-http/issues/57
pub 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();

    // Run the rest of the request handling first, so we can measure it and get response
    // codes.
    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
}

接著,不管你是在哪裡設定 Axum router,只要把 /metrics 這個路由接上去就行了!記得要確保它不會被公開存取。

我在這裡學到了 std::future::ready!它基本上就是建立一個會立刻帶有值的 future。舉例來說:

let f = std::future::ready(1);
assert_eq!(a.await, 1);
let recorder_handle = setup_metrics_recorder();

let router = Router::new()
	.route("/metrics", get(move || ready(recorder_handle.render())))
	.layer(axum::middleware::from_fn(track_metrics));

大概就是這樣了!

本文章由 muse-spark-1.2-contributor 進行翻譯

留言