1
0
Fork 0

fix metrics stuff

This commit is contained in:
Adrian Hedqvist 2023-03-26 00:30:21 +01:00
parent d076f92764
commit 9c5d3ef58e
5 changed files with 22 additions and 7 deletions

View file

@ -34,7 +34,7 @@ RUN adduser \
WORKDIR /app
COPY --from=planner /app/recipe.json .
RUN cargo chef cook --release --recipe-path recipe.json
RUN cargo chef cook --target x86_64-unknown-linux-musl --release --recipe-path recipe.json
COPY . .

View file

@ -14,7 +14,7 @@ pub mod posts;
lazy_static! {
pub static ref HIT_COUNTER: IntCounterVec =
prometheus::register_int_counter_vec!(opts!("hits", "page hits"), &["page"]).unwrap();
prometheus::register_int_counter_vec!(opts!("page_hits", "Number of hits to various pages"), &["page"]).unwrap();
}
#[instrument(skip(state))]
@ -26,7 +26,7 @@ pub async fn index(
error!("Failed rendering index: {}", e);
WebsiteError::NotFound
})?;
HIT_COUNTER.with_label_values(&["/"]);
HIT_COUNTER.with_label_values(&["/"]).inc();
Ok(Html(res.into()))
}

View file

@ -28,7 +28,7 @@ pub async fn view(
let res = render_post(&state.tera, post).await?;
HIT_COUNTER.with_label_values(&[&format!("/posts/{}/", slug)]);
HIT_COUNTER.with_label_values(&[&format!("/posts/{}/", slug)]).inc();
Ok(Html(res))
}
@ -61,6 +61,6 @@ pub async fn index(Extension(state): Extension<Arc<State>>) -> Result<Html<Strin
}
};
HIT_COUNTER.with_label_values(&["/posts/"]);
HIT_COUNTER.with_label_values(&["/posts/"]).inc();
Ok(Html(res))
}

View file

@ -1,8 +1,10 @@
use std::{collections::HashMap, sync::Arc};
use axum::{routing::get, Extension, Router};
use axum::{routing::get, Extension, Router, response::Response, body};
use color_eyre::eyre::Result;
use hyper::header::CONTENT_TYPE;
use post::Post;
use prometheus::{TextEncoder, Encoder};
use tera::Tera;
use tower_http::{compression::CompressionLayer, trace::TraceLayer};
use tracing::{instrument, log::*};
@ -49,6 +51,7 @@ pub async fn init_app() -> Result<Router> {
.nest("/posts", handlers::posts::router())
.nest_service("/static", tower_http::services::ServeDir::new("./static"))
.route("/.healthcheck", get(healthcheck))
.route("/metrics", get(metrics))
.layer(middleware);
Ok(app)
@ -58,6 +61,18 @@ async fn healthcheck() -> &'static str {
"OK"
}
async fn metrics() -> Response {
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::boxed(body::Full::from(buffer)))
.unwrap()
}
#[derive(Debug)]
pub enum WebsiteError {
NotFound,

View file

@ -138,7 +138,7 @@ mod tests {
use tera::Tera;
#[tokio::test]
async fn render_all() {
async fn render_all_posts() {
let tera = Tera::new("templates/**/*").unwrap();
let posts = super::load_all().await.unwrap();