client_rust icon indicating copy to clipboard operation
client_rust copied to clipboard

Allow construct a histogram family with a closure

Open jotare opened this issue 2 years ago • 2 comments

Hi, I'm trying to build a custom struct that wraps a couple of metrics and measure them at the same time. Something like this:

struct Observer<M> {
   count: Family<M, Counter>,
   duration: Family<M, Histogram>,
}

impl<M: Clone + Hash + Eq + PartialEq> Observer<M> {
   pub fn with_buckets(buckets: &[f64]) -> Self {
       Self {
           count: Family::<M, Counter>::default(),
           duration: Family::<M, Histogram>::new_with_constructor(|| {
               Histogram::new(buckets.iter().copied()
           }),
       }
   }

   pub fn observe(&self, label_set: M, value: f64) {
       self.count.get_or_create(&label_set).inc();
       self.duration.get_or_create(&label_set).observe(value);
   }
}

The idea is to be able to increase the counter at the same time we observe the histogram.

The problem is Family::new_with_constructor requires a function pointer. As I want dynamic buckets, I need to capture the buckets variable inside the closure and the compiler can't cast it to a function pointer anymore.

Could be possible to allow a more flexible constructor?

Thanks!

jotare avatar Oct 03 '23 15:10 jotare

I think what you're asking for can be done with a custom metric constructor. See here for details.

tylerlevine avatar Oct 11 '23 06:10 tylerlevine

As I want dynamic buckets

Is this supported by Prometheus? As far as I know, Prometheus expects Histogram buckets to be constant throughout the lifetime of a monitoring target.

mxinden avatar Oct 16 '23 12:10 mxinden