tokio_metrics/
lib.rs
1#![warn(
2 missing_debug_implementations,
3 missing_docs,
4 rust_2018_idioms,
5 unreachable_pub
6)]
7#![cfg_attr(docsrs, feature(doc_cfg))]
8#![cfg_attr(docsrs, allow(unused_attributes))]
9
10#![cfg_attr(
59 all(tokio_unstable, feature = "rt"),
60 doc = r##"
61### Monitoring runtime metrics (unstable)
62[Monitor][RuntimeMonitor] key [metrics][RuntimeMetrics] of a tokio runtime.
63**This functionality requires `tokio_unstable` and the crate feature `rt`.**
64
65In the below example, a [`RuntimeMonitor`] is [constructed][RuntimeMonitor::new] and
66three tasks are spawned and awaited; meanwhile, a fourth task prints [metrics][RuntimeMetrics]
67in 500ms [intervals][RuntimeMonitor::intervals]:
68```
69use std::time::Duration;
70
71#[tokio::main]
72async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
73 let handle = tokio::runtime::Handle::current();
74 // construct the runtime metrics monitor
75 let runtime_monitor = tokio_metrics::RuntimeMonitor::new(&handle);
76
77 // print runtime metrics every 500ms
78 {
79 tokio::spawn(async move {
80 for interval in runtime_monitor.intervals() {
81 // pretty-print the metric interval
82 println!("{:?}", interval);
83 // wait 500ms
84 tokio::time::sleep(Duration::from_millis(500)).await;
85 }
86 });
87 }
88
89 // await some tasks
90 tokio::join![
91 do_work(),
92 do_work(),
93 do_work(),
94 ];
95
96 Ok(())
97}
98
99async fn do_work() {
100 for _ in 0..25 {
101 tokio::task::yield_now().await;
102 tokio::time::sleep(Duration::from_millis(100)).await;
103 }
104}
105```
106
107### Monitoring and publishing runtime metrics (unstable)
108
109If the `metrics-rs-integration` feature is additionally enabled, this crate allows
110publishing runtime metrics externally via [metrics-rs](metrics) exporters.
111
112For example, you can use [metrics_exporter_prometheus] to make metrics visible
113to Prometheus. You can see the [metrics_exporter_prometheus] and [metrics-rs](metrics)
114docs for guidance on configuring exporters.
115
116The published metrics are the same as the fields of [RuntimeMetrics], but with
117a "tokio_" prefix added, for example `tokio_workers_count`.
118
119[metrics_exporter_prometheus]: https://docs.rs/metrics_exporter_prometheus
120[RuntimeMetrics]: crate::RuntimeMetrics
121
122This example exports Prometheus metrics by listening on a local Unix socket
123called `prometheus.sock`, which you can access for debugging by
124`curl --unix-socket prometheus.sock localhost`.
125
126```
127use std::time::Duration;
128
129#[tokio::main]
130async fn main() {
131 metrics_exporter_prometheus::PrometheusBuilder::new()
132 .with_http_uds_listener("prometheus.sock")
133 .install()
134 .unwrap();
135 tokio::task::spawn(
136 tokio_metrics::RuntimeMetricsReporterBuilder::default()
137 // the default metric sampling interval is 30 seconds, which is
138 // too long for quick tests, so have it be 1 second.
139 .with_interval(std::time::Duration::from_secs(1))
140 .describe_and_run(),
141 );
142 // Run some code
143 tokio::task::spawn(async move {
144 for _ in 0..1000 {
145 tokio::time::sleep(Duration::from_millis(10)).await;
146 }
147 })
148 .await
149 .unwrap();
150}
151```
152"##
153)]
154
155macro_rules! cfg_rt {
156 ($($item:item)*) => {
157 $(
158 #[cfg(all(tokio_unstable, feature = "rt"))]
159 #[cfg_attr(docsrs, doc(cfg(all(tokio_unstable, feature = "rt"))))]
160 $item
161 )*
162 };
163}
164
165cfg_rt! {
166 mod runtime;
167 pub use runtime::{
168 RuntimeIntervals,
169 RuntimeMetrics,
170 RuntimeMonitor,
171 };
172 #[cfg(feature = "metrics-rs-integration")]
173 pub use runtime::metrics_rs_integration::{RuntimeMetricsReporterBuilder, RuntimeMetricsReporter};
174}
175
176mod task;
177pub use task::{Instrumented, TaskMetrics, TaskMonitor};