Skip to main content

custom_publish/
custom_publish.rs

1//! A demonstration of customization of exported aggregated metrics.
2//! Using match on origin metric kind or score type to alter publication output.
3
4use dipstick::*;
5use std::time::Duration;
6
7fn main() {
8    fn custom_statistics(
9        kind: InputKind,
10        mut name: MetricName,
11        score: ScoreType,
12    ) -> Option<(InputKind, MetricName, MetricValue)> {
13        match (kind, score) {
14            // do not export gauge scores
15            (InputKind::Gauge, _) => None,
16
17            // prepend and append to metric name
18            (_, ScoreType::Count(count)) => {
19                if let Some(last) = name.pop_back() {
20                    Some((
21                        InputKind::Counter,
22                        name.append("customized_add_prefix")
23                            .append(format!("{}_and_a_suffix", last)),
24                        count,
25                    ))
26                } else {
27                    None
28                }
29            }
30
31            // scaling the score value and appending unit to name
32            (kind, ScoreType::Sum(sum)) => Some((kind, name.append("per_thousand"), sum / 1000)),
33
34            // using the unmodified metric name
35            (kind, ScoreType::Mean(avg)) => Some((kind, name, avg.round() as MetricValue)),
36
37            // do not export min and max
38            _ => None,
39        }
40    }
41
42    // send application metrics to aggregator
43    AtomicBucket::default_drain(Stream::write_to_stderr());
44    AtomicBucket::default_stats(custom_statistics);
45
46    let app_metrics = AtomicBucket::new();
47
48    // schedule aggregated metrics to be printed every 3 seconds
49    app_metrics.flush_every(Duration::from_secs(3));
50
51    let counter = app_metrics.counter("counter_a");
52    let timer = app_metrics.timer("timer_b");
53    let gauge = app_metrics.gauge("gauge_c");
54    loop {
55        counter.count(11);
56        timer.interval_us(654654);
57        gauge.value(3534);
58    }
59}