Crate prometheus_hyper[][src]

Example coding

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(&registry).expect("problem registering");

    // Startup Server
    let jh = tokio::spawn(async move {
        Server::run(
            Arc::clone(&registry),
            SocketAddr::from(([0; 4], 8080)),
            shutdown_clone.notified(),
        )
        .await
    });

    // Change Metrics
    metrics.foo.inc();

    // Shutdown
    tokio::time::sleep(Duration::from_secs(5)).await;
    shutdown.notify_one();
    jh.await.unwrap()
}

Structs

Server

Metrics Server based on tokio and hyper

Type Definitions

RegistryFn

Helper fn to register metrics