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 路由的地方,把 /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 进行翻译

评论