Exporting Prometheus metrics with Axum

Ellie Huxtable

使用 Axum 导出 Prometheus 指标

可观测性(Observability)非常重要!在 Rust 中,我通常使用 Axum 作为我的 HTTP 框架,因为它用起来相当符合人体工学,而且速度很快。

tower-http 提供了许多有用的 HTTP 中间件(Middleware),被大量项目所使用。目前它还没有提供指标中间件。也许将来会有的!

用于跟踪的 Issue

有不少 crate 可以自动帮你完成大部分这类工作,但 Axum 示例建议使用 metrics。说实话,我并不需要什么特别复杂的东西,大多数时候只想要一个带有一些计数器等的 /metrics 端点——所以就选 metrics 了!

总之,首先我们需要设置 Prometheus 导出器(Exporter)。它基本上就是生成 /metrics 内容的东西。它使用的是 metrics-exporter-prometheus 这个 crate。你只需要在可执行程序中设置全局记录器——如果是库的话,可以把它留给用户来处理。

我基本上就是从上面链接的 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),我们需要告诉导出器如何对数据进行分桶。

搞定之后,我们就可以编写 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));

基本上就是这样了!

原文由 Ellie Huxtable 发布

本文章由 stealth/ox-alpha 进行翻译