From 4b5e92345ff880f9233179191cfce1c04bd4c386 Mon Sep 17 00:00:00 2001 From: "Adam T. Carpenter" Date: Sun, 15 Sep 2024 23:18:28 -0400 Subject: feat: tracing and env vars --- src/main.rs | 40 +++++++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index 4314292..81c4427 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,9 @@ +use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter}; +use tower_http::trace::{self, TraceLayer}; +use tracing::{info, Level}; use axum::{routing::get, Router}; use tutors::fs_tutor_repo::FsTutorRepo; -use std::sync::Arc; +use std::{sync::Arc, env}; use tower_http::services::ServeDir; use posts::fs_post_repo::FsPostRepo; @@ -12,9 +15,24 @@ mod handlers; #[tokio::main] async fn main() { - let posts = Arc::new(FsPostRepo::with_dir(format!("/data/ct/{}", "blog"))); - let tutors = Arc::new(FsTutorRepo::with_dir(format!("/data/ct/{}", "team"))); + let tracing_filter = EnvFilter::builder() + .with_env_var("CT_LOG") + .try_from_env() + .unwrap_or("carpentertutoring=debug,tower_http=debug,axum::rejection=trace".into()); + tracing_subscriber::registry() + .with(tracing_filter) + .with(tracing_subscriber::fmt::layer()) + .init(); + info!("loading state..."); + let blog_dir = env::var("CT_POSTS").unwrap(); + let tutor_dir = env::var("CT_TEAM").unwrap(); + let assets_dir = env::var("CT_ASSETS").unwrap(); + + let posts = Arc::new(FsPostRepo::with_dir(blog_dir)); + let tutors = Arc::new(FsTutorRepo::with_dir(tutor_dir.clone())); + + info!("initializing router..."); let app = Router::new() .route("/", get(handlers::index_handler)) .route("/posts", get(handlers::posts_handler)) @@ -24,10 +42,18 @@ async fn main() { .route("/brochure", get(handlers::brochure_handler)) .route("/about", get(handlers::about_handler)) .with_state(tutors) - .nest_service("/assets", ServeDir::new("/data/ct/assets")) - .nest_service("/team", ServeDir::new("/data/ct/team")) - .fallback_service(ServeDir::new("static")); + .nest_service("/assets", ServeDir::new(assets_dir)) + .nest_service("/team", ServeDir::new(tutor_dir)) + .fallback_service(ServeDir::new("static")) + .layer( + TraceLayer::new_for_http() + .make_span_with(trace::DefaultMakeSpan::new() + .level(Level::INFO)) + .on_response(trace::DefaultOnResponse::new() + .level(Level::INFO)) + ); - let listener = tokio::net::TcpListener::bind("0.0.0.0:8000").await.unwrap(); + let addr = env::var("CT_BIND").unwrap_or("0.0.0.0:8000".into()); + let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); axum::serve(listener, app).await.unwrap(); } -- cgit v1.2.3