Skip to content

Commit ab152ee

Browse files
authored
docs: add example using std::io::Write (prometheus#261)
Signed-off-by: Edwin Amsler <[email protected]>
1 parent 377ca2d commit ab152ee

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

examples/io_write.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
//! Example showing how one could write to a file or socket instead of a string.
2+
//! For large metrics registries this will be more memory efficient.
3+
4+
use prometheus_client::{encoding::text::encode, metrics::counter::Counter, registry::Registry};
5+
use std::io::Write;
6+
7+
fn main() {
8+
let mut registry = <Registry>::with_prefix("stream");
9+
let request_counter: Counter<u64> = Default::default();
10+
11+
registry.register(
12+
"requests",
13+
"How many requests the application has received",
14+
request_counter.clone(),
15+
);
16+
17+
let mut buf = String::new();
18+
encode(&mut buf, &registry).unwrap();
19+
20+
let mut file = Vec::new();
21+
let mut writer = IoWriterWrapper(&mut file);
22+
encode(&mut writer, &registry).unwrap();
23+
24+
assert!(buf.as_bytes() == file);
25+
}
26+
27+
pub struct IoWriterWrapper<W>(W);
28+
29+
impl<W> std::fmt::Write for IoWriterWrapper<W>
30+
where
31+
W: Write,
32+
{
33+
fn write_str(&mut self, input: &str) -> std::fmt::Result {
34+
self.0
35+
.write_all(input.as_bytes())
36+
.map(|_| ())
37+
.map_err(|_| std::fmt::Error)
38+
}
39+
}

0 commit comments

Comments
 (0)