Skip to main content

text_format_label/
text_format_label.rs

1//! Print metrics to stderr with custom formatter including a label.
2
3use dipstick::{
4    AppLabel, Formatting, Input, InputKind, InputScope, LabelOp, LineFormat, LineOp, LineTemplate,
5    MetricName, Stream,
6};
7use std::thread::sleep;
8use std::time::Duration;
9
10/// Generates template like "$METRIC $value $label_value["abc"]\n"
11struct MyFormat;
12
13impl LineFormat for MyFormat {
14    fn template(&self, name: &MetricName, _kind: InputKind) -> LineTemplate {
15        LineTemplate::new(vec![
16            LineOp::Literal(format!("{} ", name.join(".")).to_uppercase().into()),
17            LineOp::ValueAsText,
18            LineOp::Literal(" ".into()),
19            LineOp::LabelExists(
20                "abc".into(),
21                vec![
22                    LabelOp::LabelKey,
23                    LabelOp::Literal(":".into()),
24                    LabelOp::LabelValue,
25                ],
26            ),
27            LineOp::NewLine,
28        ])
29    }
30}
31
32fn main() {
33    let counter = Stream::write_to_stderr()
34        .formatting(MyFormat)
35        .metrics()
36        .counter("counter_a");
37    AppLabel::set("abc", "xyz");
38    loop {
39        // report some metric values from our "application" loop
40        counter.count(11);
41        sleep(Duration::from_millis(500));
42    }
43}