Exporting Prometheus metrics with Axum

Ellie Huxtable

AxumでPrometheusメトリクスをエクスポートする

原文は Ellie Huxtable により に公開されました。 このブログを購読する

オブザーバビリティは重要だ!普段、RustではHTTPフレームワークとしてAxumを使っている。使いやすくて高速だからだ。

tower-httpは、多くのプロジェクトで使われている便利なHTTPミドルウェアを多数提供している。ただ現時点ではメトリクス用のミドルウェアは提供されていない。いつか提供されるかもしれない!

トラッキング用のIssue

このあたりを自動でやってくれるクレートはかなりたくさんあるが、Axumのサンプルではmetricsを使うことが推奨されている。正直、そこまで複雑なものは必要なく、ほとんどの場合はカウンターなどを備えた/metricsエンドポイントがあれば十分なので、metricsを使うことにした!

さて、まずはPrometheusエクスポーターをセットアップする必要がある。これは基本的に/metricsの中身を生成するものだ。metrics-exporter-prometheusクレートを使っている。グローバルなレコーダーをセットアップするのは実行可能ファイルでのみにすべきで、ライブラリであればその設定は利用者に任せればよい。

これはほとんど上でリンクした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()
}

今回は2つのメトリクスをセットアップするが、セットアップが必要なのはhistory_requests_duration_secondsだけだ。これはヒストグラムなので、エクスポーターにデータをどのようにバケット分けするかを伝える必要があるからだ。

これができたら、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」を使用して翻訳されました。

コメント