AxumでPrometheusメトリクスをエクスポートする
可観測性は重要です!Rustでは普段、HTTPフレームワークにRustのAxumを使っています。使い勝手がよく、それでいて高速だからです。
tower-httpは、多くのプロジェクトで使われている便利なHTTPミドルウェアを多数提供しています。ただ、現時点ではメトリクス用のミドルウェアはありません。いつか追加されるかもしれません!
追跡用の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()
}今日は実際には2つのメトリクスをセットアップしていますが、セットアップが必要なのはhistory_requests_duration_secondsだけです。これはヒストグラムなので、データをどのバケットに分けるかを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));本当に、これだけです!
記事をランダムに読む