Struct MetricLayerBuilder

Source
pub struct MetricLayerBuilder<'a, T, M, S: MetricBuilderState> { /* private fields */ }
Expand description

A builder for GenericMetricLayer that enables further customizations.

Most of the example code uses PrometheusMetricLayerBuilder, which is only a type alias specialized for Prometheus.

§Example

use axum_prometheus::PrometheusMetricLayerBuilder;

let (metric_layer, metric_handle) = PrometheusMetricLayerBuilder::new()
    .with_ignore_patterns(&["/metrics", "/sensitive"])
    .with_group_patterns_as("/foo", &["/foo/:bar", "/foo/:bar/:baz"])
    .with_group_patterns_as("/bar", &["/auth/*path"])
    .with_default_metrics()
    .build_pair();

Implementations§

Source§

impl<'a, T, M, S> MetricLayerBuilder<'a, T, M, S>
where S: MetricBuilderState,

Source

pub fn with_ignore_pattern(self, ignore_pattern: &'a str) -> Self

Skip reporting a specific route pattern.

In the following example

use axum_prometheus::PrometheusMetricLayerBuilder;

let metric_layer = PrometheusMetricLayerBuilder::new()
    .with_ignore_pattern("/metrics")
    .build();

any request that’s URI path matches “/metrics” will be skipped altogether when reporting to the external provider.

Supports the same features as axum’s Router.

Note: with_ignore_pattern and with_allow_pattern are mutually exclusive. If you call both, the last one called takes precedence and resets the previous patterns.

Note that ignore patterns are always checked before any other group pattern rule is applied and it short-circuits if a certain route is ignored.

Source

pub fn with_ignore_patterns(self, ignore_patterns: &'a [&'a str]) -> Self

Skip reporting a collection of route patterns.

Equivalent with calling with_ignore_pattern repeatedly.

use axum_prometheus::PrometheusMetricLayerBuilder;

let metric_layer = PrometheusMetricLayerBuilder::new()
    .with_ignore_patterns(&["/foo", "/bar/:baz"])
    .build();

Supports the same features as axum’s Router.

Note: with_ignore_patterns and with_allow_patterns are mutually exclusive. If you call both, the last one called takes precedence and resets the previous patterns.

Note that ignore patterns are always checked before any other group pattern rule is applied and it short-circuits if a certain route is ignored.

Source

pub fn with_allow_pattern(self, allow_pattern: &'a str) -> Self

Only report requests matching a specific route pattern.

In the following example

use axum_prometheus::PrometheusMetricLayerBuilder;

let metric_layer = PrometheusMetricLayerBuilder::new()
    .with_allow_pattern("/api/*path")
    .build();

only requests whose URI path matches “/api/*path” will be reported.

Supports the same features as axum’s Router.

Note: with_allow_pattern and with_ignore_pattern are mutually exclusive. If you call both, the last one called takes precedence and resets the previous patterns.

Source

pub fn with_allow_patterns(self, allow_patterns: &'a [&'a str]) -> Self

Only report requests matching a collection of route patterns.

Equivalent with calling with_allow_pattern repeatedly.

use axum_prometheus::PrometheusMetricLayerBuilder;

let metric_layer = PrometheusMetricLayerBuilder::new()
    .with_allow_patterns(&["/api/*path", "/public/*path"])
    .build();

Supports the same features as axum’s Router.

Note: with_allow_patterns and with_ignore_patterns are mutually exclusive. If you call both, the last one called takes precedence and resets the previous patterns.

Source

pub fn with_group_patterns_as( self, group_pattern: &'a str, patterns: &'a [&'a str], ) -> Self

Group matching route patterns and report them under the given (arbitrary) endpoint.

This feature is commonly useful for parametrized routes. Let’s say you have these two routes:

  • /foo/:bar
  • /foo/:bar/:baz

By default every unique request URL path gets reported with different endpoint label. This feature allows you to report these under a custom endpoint, for instance /foo:

use axum_prometheus::PrometheusMetricLayerBuilder;

let metric_layer = PrometheusMetricLayerBuilder::new()
    // the choice of "/foo" is arbitrary
    .with_group_patterns_as("/foo", &["/foo/:bar", "foo/:bar/:baz"])
    .build();
Source

pub fn with_endpoint_label_type(self, endpoint_label: EndpointLabel) -> Self

Determine how endpoints are reported. For more information, see EndpointLabel.

Source

pub fn enable_response_body_size(self, enable: bool) -> Self

Enable response body size tracking.

§Note:

This may introduce some performance overhead.

Source

pub fn no_initialize_metrics(self) -> Self

By default, all metrics are initialized via metrics::describe_* macros, setting descriptions and units.

This function disables this initialization.

Source§

impl<'a, T, M> MetricLayerBuilder<'a, T, M, LayerOnly>

Source

pub fn new() -> MetricLayerBuilder<'a, T, M, LayerOnly>

Initialize the builder.

Source

pub fn with_prefix(self, prefix: impl Into<Cow<'a, str>>) -> Self

Use a prefix for the metrics instead of axum. This will use the following metric names:

  • {prefix}_http_requests_total
  • {prefix}_http_requests_pending
  • {prefix}_http_requests_duration_seconds

..and will also use {prefix}_http_response_body_size, if response body size tracking is enabled.

This method will take precedence over environment variables.

§Note

This function inherently changes the metric names, beware to use the appropriate names. There’re functions in the utils module to get them at runtime.

Source§

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

Source

pub fn build(self) -> GenericMetricLayer<'a, T, M>

Finalize the builder and get the previously registered metric handle out of it.

Source§

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

Source

pub fn with_default_metrics(self) -> MetricLayerBuilder<'a, T, M, Paired>

Attach the default exporter handle to the builder. This is similar to initializing with GenericMetricLayer::pair.

After calling this function you can finalize with the build_pair method, and can no longer call build.

Source§

impl<'a, T, M> MetricLayerBuilder<'a, T, M, LayerOnly>

Source

pub fn with_metrics_from_fn( self, f: impl FnOnce() -> T, ) -> MetricLayerBuilder<'a, T, M, Paired>

Attach a custom built exporter handle to the builder that’s returned from the passed in closure.

§Example
use axum_prometheus::{
       PrometheusMetricLayerBuilder, AXUM_HTTP_REQUESTS_DURATION_SECONDS, utils::SECONDS_DURATION_BUCKETS,
};
use metrics_exporter_prometheus::{Matcher, PrometheusBuilder};

let (metric_layer, metric_handle) = PrometheusMetricLayerBuilder::new()
    .with_metrics_from_fn(|| {
        PrometheusBuilder::new()
            .set_buckets_for_metric(
                Matcher::Full(AXUM_HTTP_REQUESTS_DURATION_SECONDS.to_string()),
                SECONDS_DURATION_BUCKETS,
            )
            .unwrap()
            .install_recorder()
            .unwrap()
    })
    .build_pair();

After calling this function you can finalize with the build_pair method, and can no longer call build.

Source§

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

Source

pub fn build_pair(self) -> (GenericMetricLayer<'a, T, M>, T)

Finalize the builder and get out the GenericMetricLayer and the exporter handle out of it as a tuple.

Trait Implementations§

Source§

impl<'a, T: Clone, M: Clone, S: Clone + MetricBuilderState> Clone for MetricLayerBuilder<'a, T, M, S>

Source§

fn clone(&self) -> MetricLayerBuilder<'a, T, M, S>

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: Default, M: Default, S: Default + MetricBuilderState> Default for MetricLayerBuilder<'a, T, M, S>

Source§

fn default() -> MetricLayerBuilder<'a, T, M, S>

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

Auto Trait Implementations§

§

impl<'a, T, M, S> !Freeze for MetricLayerBuilder<'a, T, M, S>

§

impl<'a, T, M, S> !RefUnwindSafe for MetricLayerBuilder<'a, T, M, S>

§

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

§

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

§

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

§

impl<'a, T, M, S> UnwindSafe for MetricLayerBuilder<'a, T, M, S>
where T: UnwindSafe, S: 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,