use crate::context::Context;
use crate::error::Result;
use crate::middleware::{InboundAction, InboundMiddleware, OutboundMiddleware};
use async_trait::async_trait;
use std::time::Instant;
#[derive(Clone)]
pub struct LoggingMiddleware {
pub name: String,
}
impl LoggingMiddleware {
pub fn new() -> Self {
Self {
name: "request_logger".to_string(),
}
}
pub fn with_name(name: &str) -> Self {
Self {
name: name.to_string(),
}
}
}
impl Default for LoggingMiddleware {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl InboundMiddleware for LoggingMiddleware {
async fn process_request(&self, ctx: &mut Context) -> Result<InboundAction> {
if log::log_enabled!(log::Level::Info) {
let start_time = Instant::now();
let method = &ctx.req.method;
let path = ctx.req.path();
let ip = ctx.ip();
log::info!("→ {} {} from {}", method, path, ip);
let _ = ctx.set("logging_start_time", start_time);
}
Ok(InboundAction::Capture)
}
fn name(&self) -> &'static str {
"logging"
}
fn priority(&self) -> i32 {
-1000 }
}
#[async_trait]
impl OutboundMiddleware for LoggingMiddleware {
async fn process_response(&self, ctx: &mut Context) -> Result<()> {
if log::log_enabled!(log::Level::Info) {
if let Some(start_time) = ctx.get::<Instant>("logging_start_time") {
let elapsed = start_time.elapsed();
let method = &ctx.req.method;
let path = ctx.req.path();
let status = ctx.res.as_ref().map(|r| r.status.as_u16()).unwrap_or(500);
log::info!("← {} {} {} in {:?}", method, path, status, elapsed);
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::Request;
use crate::views::ViewEngine;
use std::sync::Arc;
#[tokio::test]
async fn test_logging_middleware() {
let middleware = LoggingMiddleware::new();
let mut request = Request::default();
request.method = "GET".to_string();
request.uri = "/test".to_string();
let views = Arc::new(ViewEngine::from_directory("views"));
let mut ctx = Context::new(request, views);
let action = middleware.process_request(&mut ctx).await.unwrap();
assert!(matches!(action, InboundAction::Capture));
if log::log_enabled!(log::Level::Info) {
assert!(ctx.get::<Instant>("logging_start_time").is_some());
}
middleware.process_response(&mut ctx).await.unwrap();
}
#[tokio::test]
async fn test_logging_middleware_minimal_overhead() {
let middleware = LoggingMiddleware::new();
let mut request = Request::default();
request.method = "POST".to_string();
request.uri = "/api/data".to_string();
let views = Arc::new(ViewEngine::from_directory("views"));
let mut ctx = Context::new(request, views);
let start = Instant::now();
let _ = middleware.process_request(&mut ctx).await.unwrap();
let inbound_duration = start.elapsed();
let start = Instant::now();
let _ = middleware.process_response(&mut ctx).await.unwrap();
let outbound_duration = start.elapsed();
let total = inbound_duration + outbound_duration;
assert!(
total.as_micros() < 100,
"Logging middleware overhead too high: {:?}",
total
);
}
}