From bc2b74c401057d566a49159f4d0d0f10bacf7768 Mon Sep 17 00:00:00 2001 From: itsscb Date: Sun, 25 Aug 2024 20:07:57 +0200 Subject: [PATCH] feat: add logging --- Cargo.toml | 6 ++---- src/main.rs | 32 ++++++++++++++++++++++++++------ 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 34c20b1..cc6c9aa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,11 +11,9 @@ shuttle-axum = "0.45.0" shuttle-runtime = "0.45.0" tokio = "1.28.2" tower-http = { version = "0.5.2", features = ["fs", "cors"] } +tracing = "0.1.40" yew = "0.21.0" [workspace] -members = [ - ".", - "frontend", -] +members = [".", "frontend"] diff --git a/src/main.rs b/src/main.rs index 81e9603..58bb257 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,21 +1,29 @@ -use axum::{routing::get, Router}; -use rand::seq::SliceRandom; -use tower_http::services::ServeDir; -use tower_http::cors::{Any,CorsLayer}; +use axum::{ + body::Body, + http::Request, + middleware::{self, Next}, + response::Response, + routing::get, + Router, +}; use http::Method; +use rand::seq::SliceRandom; +use std::net::SocketAddr; +use tower_http::cors::{Any, CorsLayer}; +use tower_http::services::ServeDir; +use tracing::info; #[shuttle_runtime::main] async fn main() -> shuttle_axum::ShuttleAxum { - let cors = CorsLayer::new() .allow_origin(Any) // Allow all origins; adjust as necessary .allow_methods(vec![Method::GET]) // Specify allowed methods .allow_headers(Any); let router = Router::new() - // .route("/", get(hello_world)) .nest_service("/", ServeDir::new("frontend/dist")) .route("/word", get(word)) + .layer(middleware::from_fn(log_ip)) .layer(cors); Ok(router.into()) @@ -26,6 +34,18 @@ async fn word() -> String { WORDS.choose(&mut rng).unwrap().to_string() } +async fn log_ip(req: Request, next: Next) -> Response { + if let Some(addr) = req.extensions().get::() { + info!( + PATH = req.uri().path().to_string(), + IP = addr.ip().to_string() + ); + } else { + info!(PATH = req.uri().path().to_string()); + } + next.run(req).await +} + static WORDS: &[&str; 5921] = &[ "aalen", "Aales", "aalst", "aalte", "Aarau", "Aaron", "Aasee", "Aases", "Abart", "abbat", "Abbau", "Abbey", "abbog", "Abdul", "Abeba", "Abels", "Abend", "abgab", "Abgas", "abhob",