Crate axum_metrics

Source
Expand description

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.

Structs§

ExtraMetricLabels
An http extension to add extra metric labels.
Metric
Middleware that instrument metrics on all requests and responses.
MetricLayer
Layer for applying Metric.
RequestBody
Request body for Metric.
ResponseBody
Response body for Metric.
ResponseFuture
Response future for Metric.