use metriken::{AtomicHistogram, MetricEntry, RwLockHistogram, Value};
use crate::Snapshot;
pub struct Snapshotter {
filter: fn(&MetricEntry) -> bool,
}
#[derive(Default)]
pub struct SnapshotterBuilder {
snapshotter: Snapshotter,
}
impl SnapshotterBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn build(self) -> Snapshotter {
self.snapshotter
}
pub fn filter(mut self, filter: fn(&MetricEntry) -> bool) -> Self {
self.snapshotter.filter = filter;
self
}
}
impl Default for Snapshotter {
fn default() -> Self {
Self { filter: |_| true }
}
}
impl Snapshotter {
pub fn snapshot(&self) -> Snapshot {
let mut snapshot = Snapshot::new();
for metric in &metriken::metrics() {
if !(self.filter)(metric) {
continue;
}
match metric.value() {
Some(Value::Counter(value)) => {
snapshot
.counters
.push((metric.formatted(metriken::Format::Simple), value));
}
Some(Value::Gauge(value)) => {
snapshot
.gauges
.push((metric.formatted(metriken::Format::Simple), value));
}
Some(Value::Other(other)) => {
if let Some(histogram) = other.downcast_ref::<AtomicHistogram>() {
if let Some(histogram) = histogram.snapshot() {
snapshot
.histograms
.push((metric.formatted(metriken::Format::Simple), histogram));
}
} else if let Some(histogram) = other.downcast_ref::<RwLockHistogram>() {
if let Some(histogram) = histogram.snapshot() {
snapshot
.histograms
.push((metric.formatted(metriken::Format::Simple), histogram));
}
}
}
_ => continue,
}
}
snapshot
}
}