Crate prometrics_sb

Source
Expand description

§prometrics_sb

A library for reducing the code using the Axum and prometheus web server. Example of use:

use axum::{
   extract::Request, extract::State, http::StatusCode, response::Json, routing::get, Router,
};
use lazy_static::lazy_static;
use prometrics_sb::axpromlib::{
   auth, get_str_var, load_env, run_metrics, Atp, Selfcounter, Selfgauge, Selfhistogramvec, run_prom
};
use prometrics_sb::{create_counter, create_gauge, create_histogram_vec, create_pool};
use serde_json::Value;

lazy_static! {
   static ref COUNTER: Selfcounter = create_counter!("qwe_asd", "test counter");
   static ref GAUGE: Selfgauge = create_gauge!("asd_zxc", "test gauge");
   static ref HV: Selfhistogramvec =
       create_histogram_vec!("rty_fgh", "test histogram vec", "handler");
}

async fn hello_handler(State(pool): State<Atp>, req: Request) -> Result<Json<Value>, StatusCode> {
  pool.handle_request(move || {
       COUNTER.inc();
       GAUGE.add(23.);
       let timer = HV.start_timer("all".to_string());
       match auth(req) {
           Ok(true) => {}
           Err(_err) => return Err(StatusCode::UNAUTHORIZED),
           _ => {}
       }

       let data = r#"
       {
         "pro": "metrics"
       }"#;

       HV.observe(timer);
       Ok(Json(serde_json::from_str(data).unwrap()))
   })
   .await?
}

#[tokio::main]
async fn main() {
    load_env();
    //start_sender(5, "job", "name", "value", "127.0.0.1:9090", "username", "pass");
    run_prom("0.0.0.0:8081");
    let app = Router::new()
       //.route("/metrics", get(run_metrics)) or use it
       .route("/", get(hello_handler))
       .with_state(create_pool!(get_str_var("MAX_THREADS").parse().unwrap()));

   let listener = tokio::net::TcpListener::bind("0.0.0.0:".to_string() + &get_str_var("PORT"))
       .await
       .unwrap();
   axum::serve(listener, app).await.unwrap();
}

Dependencies:

[dependencies]
axum = "0.7.7"
tokio = { version = "1.40.0", features = ["full"] }
lazy_static = "^1.4"
serde_json = { version = "1.0.128", default-features = false, features = ["alloc"] }
prometrics_sb = "0.1.2"
tower = "0.5.1"

Modules§

axpromlib
axumsync
custommetric

Macros§

create_counter
Macro for simple create Selfcounter
create_gauge
Macro for simple create Selfgauge
create_histogram_vec
Macro for simple create Selfhistogramvec
create_pool
Macro for simple create thread pool