metrics-rs / metrics

A metrics ecosystem for Rust.
MIT License
1.13k stars 158 forks source link

Macro to increment-and-then-decrement a gauge? #335

Closed stuhood closed 1 year ago

stuhood commented 1 year ago

I am using the following macro to increment-and-then-decrement a gauge, and was wondering whether a better pattern already exists in the library that I've missed:

pub struct GaugeDecrement<F: FnOnce() -> ()>(Option<F>);

impl<F: FnOnce() -> ()> GaugeDecrement<F> {
    pub fn new(f: F) -> Self {
        GaugeDecrement(Some(f))
    }
}

impl<F: FnOnce() -> ()> Drop for GaugeDecrement<F> {
    fn drop(&mut self) {
        self.0.take().unwrap()()
    }
}

/// Temporarily increments a gauge, and returns a guard that will decrement the metric when
/// dropped.
#[macro_export]
macro_rules! with_incremented_gauge {
    ($name:literal, $value:literal $($tail:tt)*) => {{
        metrics::increment_gauge!($name, $value $($tail)*);

        $crate::GaugeDecrement::new(|| metrics::decrement_gauge!($name, $value $($tail)*))
    }};
}
tobz commented 1 year ago

Nope, you haven't missed any other pattern/approach for doing this. :) If I was going to write something for metrics itself, this is likely how I'd approach it.