Skip to content

Registering the same metric multiple times #495

@sazzer

Description

@sazzer

I've written some Axum middleware to record the number of times each HTTP request is processed, and I'm hitting problems with actually recording the metrics.

What I've done so far is this:

pub async fn record_metrics<B>(
    registry: Extension<prometheus::Registry>,
    request: Request<B>,
    next: Next<B>,
) -> Response {
    let uri = request.uri().to_string();

    let response = next.run(request).await;

    let counter = CounterVec::new(Opts::new("http_request", "HTTP Requests"), &["uri", "status_code"]).unwrap();
    registry.register(Box::new(counter.clone())).unwrap();

    counter.with_label_values(&[&uri, response.status().as_str()]).inc();

    response
}

And the call to registry.register() returns AlreadyReg on all incoming requests after the first one.

Is there some easy way to get back the already registered metric so that I can increment that instead?

I've looked at calling registry.gather() to try and find it, but can't trivially work out how to find the correct entry in the returned set.

Cheers

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions