There are quite a few crates that do a lot of this automagically for you, but the Axum example suggests using metrics. I honestly don’t need anything extra complex and just want a /metrics endpoint with some counters/etc most of the time - so metrics it is!
Anyway, first we need to setup the prometheus exporter. This is basically what generates the content of /metrics. It uses the metrics-exporter-prometheus crate. You’ll only want to set up a global recorder in an executable - for a library, you can leave that up to the user.
I’ve mostly just lifted this from the Axum example linked above 😇
I’m actually setting up two metrics today, but only history_requests_duration_seconds requires some setup. This is because it is a histogram, and we need to tell the exporter how to bucket the data.
Once that’s done, we can write the axum middleware! (lifted from the example, and modified to compile properly. I’ll open a PR)
Then, wherever you setup your Axum router, plug in the /metrics route! You’ll need to make sure it’s not publicly available.
I learned about std::future::ready here! It basically creates a future that is immediately available with a value. For example: