#metrics #axum #prometheus

axum-metrics

Minimalist exporter-agnostic metrics instrumentation middleware for axum

1 unstable release

0.1.0 Oct 14, 2024

#331 in Debugging

Download history 183/week @ 2024-10-12 14/week @ 2024-10-19 9/week @ 2024-11-02

206 downloads per month

MIT/Apache

15KB
254 lines

axum-metrics

Minimalist exporter-agnostic metrics instrumentation middleware for axum.

Crates.io Documentation

See docs for more details.


lib.rs:

Minimalist exporter-agnostic metrics instrumentation middleware for axum.

Note that we does not set metrics::Recorder backend automatically. You must pick and install a metrics exporter like metrics_exporter_prometheus to perform actualy statistics and export the result.

use axum::routing::get;
use metrics_exporter_prometheus::PrometheusBuilder;
use tokio::net::TcpListener;

#[tokio::main]
async fn main() {
    // Install a metrics exporter backend and expose metrics on 127.0.0.1:8050.
    // This also spawns a upkeeping thread for maintenance of histogram data.
    PrometheusBuilder::new()
        .with_http_listener(([127, 0, 0, 1], 8050))
        .install()
        .unwrap();

    let router = axum::Router::new()
        .route("/", get(|| async { "hello world" }))
        // Instrument for metrics.
        .layer(axum_metrics::MetricLayer::default());

    // Run the main server on 0.0.0.0:8000.
    let listener = TcpListener::bind("0.0.0.0:8000").await.unwrap();
    axum::serve(listener, router).await.unwrap();
}

Metrics

The metric and label names are heavily inspired by caddy.

Following metrics are recorded:

  • gauge http_requests_in_flight: the number of in-flight requests. Streaming responses are counted until the full stream completes.
  • counter http_requests_total: the number of all requests ever processed. This is currently records after the response completes for simplicity.
  • histogram http_request_size_bytes: body size of requests in bytes. If the request is only half-read, then the number of actual read bytes is recorded.
  • histogram http_response_size_bytes: body size of requests in bytes. If the response is only half-written, then the number of actual written bytes is recorded.
  • histogram http_request_duration_seconds: time of round-trip of request in seconds. This is measured from request received to the end of response body stream.
  • histogram http_response_duration_seconds: time to first-byte of responss in seconds. This is measured from request received to the response future becomes ready.

Following labels are attached to relavent metrics:

  • endpoint: the matched route template (MatchedPath), or unknown otherwise.
  • method: the request method.
  • code: the response status code.
  • Additional labels from ExtraMetricLabels extension of Request or Response, if exists.

Dependencies

~3.5–5MB
~90K SLoC