Skip to main content

rustbasic_core/middleware/
logging.rs

1/* ---------------------------------------------------------
2 * 📑 LABEL: LOGGING MIDDLEWARE
3 * Mencatat setiap request yang masuk beserta IP pengunjung.
4 * Juga mencatat IP ke dalam tracker sesi untuk keamanan database.
5 * --------------------------------------------------------- */
6
7use axum::{
8    body::Body,
9    extract::ConnectInfo,
10    http::Request,
11    middleware::Next,
12    response::Response,
13};
14use colored::*;
15use axum_session::Session;
16use crate::session_manager::{RustBasicSessionStore, IP_TRACKER};
17use std::net::SocketAddr;
18
19pub async fn logging_middleware(
20    ConnectInfo(addr): ConnectInfo<SocketAddr>,
21    session: Session<RustBasicSessionStore>,
22    req: Request<Body>,
23    next: Next,
24) -> Response {
25    let method = req.method().clone();
26    let path = req.uri().path().to_string();
27    let ip = addr.ip().to_string();
28
29    // 1. Simpan IP ke tracker
30    IP_TRACKER.insert(session.get_session_id().to_string(), ip.clone());
31
32    // 2. Log ke Terminal (Format: [HTTP] TIMESTAMP METHOD PATH from IP)
33    let method_str = method.as_str();
34    let method_colored = match method_str {
35        "GET" => method_str.green(),
36        "POST" => method_str.blue(),
37        "PUT" => method_str.yellow(),
38        "DELETE" => method_str.red(),
39        _ => method_str.white(),
40    };
41
42    println!(
43        "[{}] {} {:<6} {} from {}",
44        "HTTP".magenta().bold(),
45        chrono::Local::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string().dimmed(),
46        method_colored.bold(),
47        path.cyan(),
48        ip.yellow()
49    );
50
51    // 3. Log ke File (Tanpa warna via tracing)
52    tracing::info!(method = %method, path = %path, ip = %ip, "Request");
53
54    next.run(req).await
55}