Exporting Prometheus metrics with Axum

Ellie Huxtable

使用 Axum 匯出 Prometheus 指標

Observability(可觀測性)非常重要!我通常在 Rust 中使用 Axum 作為我的 HTTP 框架,因為它用起來相當符合人體工學,而且速度很快。

tower-http 提供了許多在大量專案中使用的實用 HTTP middleware(中介軟體)。目前它尚未提供 metrics(指標) middleware。也許未來會提供!

追蹤用 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()
}

我今天實際上設定了兩個 metrics,但只有 history_requests_duration_seconds 需要額外設定。這是因為它是一個 histogram(直方圖),我們需要告訴 exporter 要如何對資料進行分桶。

完成之後,我們就可以撰寫 Axum middleware 了!(取自範例,並修改為可正常編譯。我會去提交一個 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));

大致上就是這樣了!

原文由 Ellie Huxtable 發布

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