use prometheus::{IntCounter, Opts, Registry};
use prometheus_hyper::{RegistryFn, Server};
use std::{error::Error, net::SocketAddr, sync::Arc, time::Duration};
use tokio::sync::Notify;
pub struct CustomMetrics {
pub foo: IntCounter,
}
impl CustomMetrics {
pub fn new() -> Result<(Self, RegistryFn), Box<dyn Error>> {
let foo = IntCounter::with_opts(Opts::new("foo", "description"))?;
let foo_clone = foo.clone();
let f = |r: &Registry| r.register(Box::new(foo_clone));
Ok((Self { foo }, Box::new(f)))
}
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> std::result::Result<(), hyper::Error> {
let registry = Arc::new(Registry::new());
let shutdown = Arc::new(Notify::new());
let shutdown_clone = Arc::clone(&shutdown);
let (metrics, f) = CustomMetrics::new().expect("failed prometheus");
f(®istry).expect("problem registering");
let jh = tokio::spawn(async move {
Server::run(
Arc::clone(®istry),
SocketAddr::from(([0; 4], 8080)),
shutdown_clone.notified(),
)
.await
});
metrics.foo.inc();
tokio::time::sleep(Duration::from_secs(5)).await;
shutdown.notify_one();
jh.await.unwrap()
}