Struct GenericMetricLayer

Source
pub struct GenericMetricLayer<'a, T, M> { /* private fields */ }
Expand description

The tower middleware layer for recording http metrics with different exporters.

Implementations§

Source§

impl<'a, T, M> GenericMetricLayer<'a, T, M>
where M: MakeDefaultHandle<Out = T>,

Source

pub fn new() -> Self

Create a new tower middleware that can be used to track metrics.

By default, this will not “install” the exporter which sets it as the global recorder for all metrics calls. If you’re using Prometheus, here you can use metrics_exporter_prometheus::PrometheusBuilder to build your own customized metrics exporter.

This middleware is using the following constants for identifying different HTTP metrics:

In terms of setup, the most important one is AXUM_HTTP_REQUESTS_DURATION_SECONDS, which is a histogram metric used for request latency. You may set customized buckets tailored for your used case here.

§Example
use axum::{routing::get, Router};
use axum_prometheus::{AXUM_HTTP_REQUESTS_DURATION_SECONDS, utils::SECONDS_DURATION_BUCKETS, PrometheusMetricLayer};
use metrics_exporter_prometheus::{Matcher, PrometheusBuilder};
use std::net::SocketAddr;

#[tokio::main]
async fn main() {
    let metric_layer = PrometheusMetricLayer::new();
    // This is the default if you use `PrometheusMetricLayer::pair`.
    let metric_handle = PrometheusBuilder::new()
       .set_buckets_for_metric(
           Matcher::Full(AXUM_HTTP_REQUESTS_DURATION_SECONDS.to_string()),
           SECONDS_DURATION_BUCKETS,
       )
       .unwrap()
       .install_recorder()
       .unwrap();

    let app = Router::<()>::new()
      .route("/fast", get(|| async {}))
      .route(
          "/slow",
          get(|| async {
              tokio::time::sleep(std::time::Duration::from_secs(1)).await;
          }),
      )
      .route("/metrics", get(|| async move { metric_handle.render() }))
      .layer(metric_layer);

   // Run the server as usual:
   // let listener = tokio::net::TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 3000)))
   //     .await
   //     .unwrap();
   // axum::serve(listener, app).await.unwrap()
}
Source

pub fn enable_response_body_size(&mut self)

Enable tracking response body sizes.

Source

pub fn pair_from(m: M) -> (Self, T)

Crate a new tower middleware and a default exporter from the provided value of the passed in argument.

This function is useful when additional data needs to be injected into MakeDefaultHandle::make_default_handle.

§Example
use axum_prometheus::{GenericMetricLayer, MakeDefaultHandle};

struct Recorder { host: String }

impl MakeDefaultHandle for Recorder {
    type Out = ();

    fn make_default_handle(self) -> Self::Out {
        // Perform the initialization. `self` is passed in by value.
        todo!();
    }
}

fn main() {
    let (metric_layer, metric_handle) = GenericMetricLayer::pair_from(
        Recorder { host: "0.0.0.0".to_string() }
    );
}
Source§

impl<'a, T, M> GenericMetricLayer<'a, T, M>
where M: MakeDefaultHandle<Out = T> + Default,

Source

pub fn pair() -> (Self, T)

Crate a new tower middleware and a default global Prometheus exporter with sensible defaults.

If used with a custom exporter that’s different from Prometheus, the exporter struct must implement MakeDefaultHandle + Default.

§Example
use axum::{routing::get, Router};
use axum_prometheus::PrometheusMetricLayer;
use std::net::SocketAddr;

#[tokio::main]
async fn main() {
    let (metric_layer, metric_handle) = PrometheusMetricLayer::pair();

    let app = Router::<()>::new()
      .route("/fast", get(|| async {}))
      .route(
          "/slow",
          get(|| async {
              tokio::time::sleep(std::time::Duration::from_secs(1)).await;
          }),
      )
      .route("/metrics", get(|| async move { metric_handle.render() }))
      .layer(metric_layer);

   // Run the server as usual:
   // let listener = tokio::net::TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 3000)))
   //     .await
   //     .unwrap();
   // axum::serve(listener, app).await.unwrap()
}

Trait Implementations§

Source§

impl<'a, T, M> Clone for GenericMetricLayer<'a, T, M>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'a, T, M> Default for GenericMetricLayer<'a, T, M>
where M: MakeDefaultHandle<Out = T>,

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'a, S, T, M> Layer<S> for GenericMetricLayer<'a, T, M>

Source§

type Service = LifeCycle<S, SharedClassifier<StatusInRangeAsFailures>, Traffic<'a>, Option<BodySizeRecorder>>

The wrapped service
Source§

fn layer(&self, inner: S) -> Self::Service

Wrap the given service with the middleware, returning a new service that has been decorated with the middleware.

Auto Trait Implementations§

§

impl<'a, T, M> !Freeze for GenericMetricLayer<'a, T, M>

§

impl<'a, T, M> !RefUnwindSafe for GenericMetricLayer<'a, T, M>

§

impl<'a, T, M> Send for GenericMetricLayer<'a, T, M>
where T: Send, M: Send,

§

impl<'a, T, M> Sync for GenericMetricLayer<'a, T, M>
where T: Sync, M: Sync,

§

impl<'a, T, M> Unpin for GenericMetricLayer<'a, T, M>
where T: Unpin, M: Unpin,

§

impl<'a, T, M> UnwindSafe for GenericMetricLayer<'a, T, M>
where T: UnwindSafe, M: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,