|
| 1 | +use std::fmt::Error; |
| 2 | +use std::sync::{Arc, Mutex}; |
| 3 | +use std::sync::atomic::AtomicU64; |
| 4 | +use std::thread; |
| 5 | +use std::time::Duration; |
| 6 | +use tokio::time::Instant; |
| 7 | +use prometheus_client::encoding::{text::encode, EncodeMetric, MetricEncoder}; |
| 8 | +use prometheus_client::metrics::family::Family; |
| 9 | +use prometheus_client::metrics::{MetricType, TypedMetric}; |
| 10 | +use prometheus_client::metrics::counter::Atomic; |
| 11 | +use prometheus_client::registry::Registry; |
| 12 | +use prometheus_client_derive_encode::EncodeLabelSet; |
| 13 | + |
| 14 | +#[derive(Default, Debug)] |
| 15 | +struct MyCounter { |
| 16 | + value: Arc<AtomicU64>, |
| 17 | + last_access: Arc<Mutex<Option<Instant>>> |
| 18 | +} |
| 19 | + |
| 20 | +impl TypedMetric for MyCounter { |
| 21 | + |
| 22 | +} |
| 23 | + |
| 24 | +impl MyCounter { |
| 25 | + pub fn get(&self) -> u64 { |
| 26 | + self.value.get() |
| 27 | + } |
| 28 | + pub fn inc(&self) -> u64 { |
| 29 | + let mut last = self.last_access.lock().unwrap(); |
| 30 | + *last = Some(Instant::now()); |
| 31 | + self.value.inc() |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +impl EncodeMetric for MyCounter { |
| 36 | + fn encode(&self, mut encoder: MetricEncoder) -> Result<(), Error> { |
| 37 | + encoder.encode_counter::<(), _, u64>(&self.get(), None) |
| 38 | + } |
| 39 | + |
| 40 | + fn metric_type(&self) -> MetricType { |
| 41 | + todo!() |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +#[derive(Clone, Hash, Default, Debug, PartialEq, Eq, EncodeLabelSet)] |
| 46 | +struct Labels { |
| 47 | + name: String |
| 48 | +} |
| 49 | + |
| 50 | +fn main() { |
| 51 | + let mut registry = Registry::default(); |
| 52 | + |
| 53 | + let metric: Family<Labels, MyCounter> = Family::default(); |
| 54 | + registry.register( |
| 55 | + "my_custom_metric", |
| 56 | + "test", |
| 57 | + metric.clone(), |
| 58 | + ); |
| 59 | + metric.get_or_create(&Labels{name: "apple".to_string()}).inc(); |
| 60 | + metric.get_or_create(&Labels{name: "banana".to_string()}).inc(); |
| 61 | + |
| 62 | + let mut encoded = String::new(); |
| 63 | + encode(&mut encoded, ®istry).unwrap(); |
| 64 | + |
| 65 | + println!("Scrape output:\n{}", encoded); |
| 66 | + thread::sleep(Duration::from_secs(1)); |
| 67 | + metric.get_or_create(&Labels{name: "banana".to_string()}).inc(); |
| 68 | + let now = Instant::now(); |
| 69 | + metric.retain(|a, b | { |
| 70 | + let last = b.last_access.lock().unwrap().unwrap(); |
| 71 | + now.saturating_duration_since(last) > Duration::from_secs(1) |
| 72 | + }); |
| 73 | + |
| 74 | + let mut encoded = String::new(); |
| 75 | + encode(&mut encoded, ®istry).unwrap(); |
| 76 | + |
| 77 | + println!("Scrape output:\n{}", encoded); |
| 78 | +} |
0 commit comments