dipstick/examples/basics.rs

51 lines
1.6 KiB
Rust
Raw Normal View History

2017-09-25 15:48:25 +00:00
//! An app demonstrating the basics of the metrics front-end.
//! Defines metrics of each kind and use them to print values to the console in multiple ways.
2020-05-25 13:12:24 +00:00
use dipstick::{time, Input, InputScope, Prefixed, Stream};
2018-06-26 15:46:55 +00:00
use std::io;
2019-03-18 01:42:00 +00:00
use std::thread::sleep;
2017-09-25 15:48:25 +00:00
use std::time::Duration;
fn main() {
// for this demo, print metric values to the console
let app_metrics = Stream::write_to(io::stdout()).metrics();
2017-09-25 15:48:25 +00:00
// metrics can be predefined by type and name
let counter = app_metrics.counter("counter_a");
2019-01-13 17:49:24 +00:00
let level = app_metrics.level("level_a");
2017-09-25 15:48:25 +00:00
let timer = app_metrics.timer("timer_b");
2018-06-19 19:27:26 +00:00
// metrics can also be declared and used ad-hoc (use output.cache() if this happens often)
2017-09-25 15:48:25 +00:00
app_metrics.counter("just_once").count(4);
// metric names can be prepended with a common prefix
let prefixed_metrics = app_metrics.named("subsystem");
2017-09-29 20:08:28 +00:00
let event = prefixed_metrics.marker("event_c");
2017-09-25 15:48:25 +00:00
let gauge = prefixed_metrics.gauge("gauge_d");
// each kind of metric has a different method name to prevent errors
counter.count(11);
2019-01-13 17:49:24 +00:00
level.adjust(-4);
level.adjust(5);
2017-09-25 15:48:25 +00:00
gauge.value(22);
2019-01-13 17:49:24 +00:00
gauge.value(-24);
2017-09-25 15:48:25 +00:00
event.mark();
// time can be measured multiple equivalent ways:
2019-01-13 17:49:24 +00:00
// in microseconds (used internally)
timer.interval_us(35573);
2017-09-25 15:48:25 +00:00
// using the time! macro
time!(timer, sleep(Duration::from_millis(5)));
// using a closure
timer.time(|| sleep(Duration::from_millis(5)));
2019-01-13 17:49:24 +00:00
// using a "time handle"
2017-09-25 15:48:25 +00:00
let start_time = timer.start();
2022-12-15 17:20:46 +00:00
sleep(Duration::from_millis(5));
2017-09-25 15:48:25 +00:00
timer.stop(start_time);
}