enable prometheus metrics

Signed-off-by: Christine Dodrill <me@christine.website>
This commit is contained in:
Cadey Ratio 2021-04-02 21:15:25 -04:00
parent 1413226358
commit ae69dcba4f
3 changed files with 23 additions and 5 deletions

1
Cargo.lock generated
View File

@ -720,6 +720,7 @@ name = "printerfacts"
version = "0.3.0" version = "0.3.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"hyper",
"lazy_static", "lazy_static",
"mime", "mime",
"pfacts", "pfacts",

View File

@ -9,6 +9,7 @@ build = "build.rs"
[dependencies] [dependencies]
anyhow = "1" anyhow = "1"
hyper = "0.14"
lazy_static = "1.4" lazy_static = "1.4"
mime = "0.3.0" mime = "0.3.0"
pfacts = "0.1.0" pfacts = "0.1.0"

View File

@ -1,20 +1,23 @@
use crate::templates::RenderRucte; use crate::templates::RenderRucte;
use hyper::{header::CONTENT_TYPE, Body, Response};
use lazy_static::lazy_static; use lazy_static::lazy_static;
use pfacts::Facts; use pfacts::Facts;
use prometheus::{opts, register_int_counter_vec, IntCounterVec}; use prometheus::{opts, register_int_counter_vec, Encoder, IntCounterVec, TextEncoder};
use rand::prelude::*; use rand::prelude::*;
use std::{convert::Infallible, str::FromStr}; use std::{convert::Infallible, str::FromStr};
use tokio::net::UnixListener; use tokio::net::UnixListener;
use tokio_stream::wrappers::UnixListenerStream; use tokio_stream::wrappers::UnixListenerStream;
use warp::{http::Response, Filter, Rejection, Reply}; use warp::{Filter, Rejection, Reply};
include!(concat!(env!("OUT_DIR"), "/templates.rs")); include!(concat!(env!("OUT_DIR"), "/templates.rs"));
const APPLICATION_NAME: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")); const APPLICATION_NAME: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));
lazy_static! { lazy_static! {
static ref HIT_COUNTER: IntCounterVec = static ref HIT_COUNTER: IntCounterVec = register_int_counter_vec!(
register_int_counter_vec!(opts!("hits", "Number of hits to various pages"), &["page"]) opts!("printerfacts_hits", "Number of hits to various pages"),
&["page"]
)
.unwrap(); .unwrap();
} }
@ -60,10 +63,23 @@ async fn main() -> anyhow::Result<()> {
let not_found_handler = warp::any().and_then(not_found); let not_found_handler = warp::any().and_then(not_found);
let metrics_endpoint = warp::path("metrics").and(warp::path::end()).map(move || {
let encoder = TextEncoder::new();
let metric_families = prometheus::gather();
let mut buffer = vec![];
encoder.encode(&metric_families, &mut buffer).unwrap();
Response::builder()
.status(200)
.header(CONTENT_TYPE, encoder.format_type())
.body(Body::from(buffer))
.unwrap()
});
let server = warp::serve( let server = warp::serve(
fact_handler fact_handler
.or(index_handler) .or(index_handler)
.or(files) .or(files)
.or(metrics_endpoint)
.or(not_found_handler) .or(not_found_handler)
.with(warp::log(APPLICATION_NAME)), .with(warp::log(APPLICATION_NAME)),
); );