axlogger 0.1.0

A lightweight, configurable request logging middleware for Axum.
Documentation
//! `axlogger` — A simple, configurable request logger for Axum.
//!
//! Logs each HTTP request in this format:
//!
//! `PROJECT | METHOD | PATH | STATUS | DURATION | TIMESTAMP`
//!
//! The displayed fields can be configured through `logger_config.toml`
//! without recompiling the application.

use axum::{body::Body, extract::Request, middleware::Next, response::Response};
use chrono::Local;
use serde::Deserialize;
use std::{sync::OnceLock, time::Instant};

/// All logger configuration options.
///
/// These settings are loaded from the `[logger]` section of `logger_config.toml`.
/// If the file does not exist or any field is missing, default values are used.
#[derive(Debug, Deserialize, Clone)]
pub struct LoggerConfig {
    /// The project name displayed in the terminal log output.
    #[serde(default = "default_project_name")]
    pub project_name: String,

    /// Show or hide the project name.
    #[serde(default = "default_true")]
    pub show_project_name: bool,

    /// Show or hide the HTTP method.
    #[serde(default = "default_true")]
    pub show_method: bool,

    /// Show or hide the request path.
    #[serde(default = "default_true")]
    pub show_path: bool,

    /// Show or hide the HTTP status code.
    #[serde(default = "default_true")]
    pub show_status: bool,

    /// Show or hide the request duration.
    #[serde(default = "default_true")]
    pub show_duration: bool,

    /// Show or hide the timestamp.
    #[serde(default = "default_true")]
    pub show_timestamp: bool,

    /// Show or hide the query string in the request path.
    ///
    /// Example:
    /// `/users?id=1` instead of `/users`
    #[serde(default)]
    pub show_query_string: bool,

    /// Colorize terminal output based on status code.
    #[serde(default = "default_true")]
    pub colored: bool,
}

fn default_true() -> bool {
    true
}

fn default_project_name() -> String {
    "app".to_string()
}

impl Default for LoggerConfig {
    fn default() -> Self {
        Self {
            project_name: default_project_name(),
            show_project_name: true,
            show_method: true,
            show_path: true,
            show_status: true,
            show_duration: true,
            show_timestamp: true,
            show_query_string: false,
            colored: true,
        }
    }
}

#[derive(Debug, Deserialize, Default)]
struct ConfigFile {
    #[serde(default)]
    logger: LoggerConfig,
}

static CONFIG: OnceLock<LoggerConfig> = OnceLock::new();

/// Loads the configuration file and initializes global logger settings.
///
/// This function should be called once in `main()` before starting the server.
///
/// If the configuration file is missing or invalid, the logger falls back to
/// the default configuration so logging does not crash the server.
pub fn init_logger_config(path: &str) {
    let config = match std::fs::read_to_string(path) {
        Ok(content) => match toml::from_str::<ConfigFile>(&content) {
            Ok(parsed) => parsed.logger,
            Err(error) => {
                eprintln!(
                    "axlogger: failed to parse config file `{}`: {}. Using defaults.",
                    path, error
                );
                LoggerConfig::default()
            }
        },
        Err(_) => LoggerConfig::default(),
    };

    // Safe to call multiple times.
    // If already initialized, later calls are ignored.
    let _ = CONFIG.set(config);
}

fn get_config() -> &'static LoggerConfig {
    CONFIG.get_or_init(LoggerConfig::default)
}

const RESET: &str = "\x1b[0m";
const BOLD: &str = "\x1b[1m";
const DIM: &str = "\x1b[2m";

fn status_color(code: u16) -> &'static str {
    match code {
        100..=199 => "\x1b[34m", // blue
        200..=299 => "\x1b[32m", // green
        300..=399 => "\x1b[36m", // cyan
        400..=499 => "\x1b[33m", // yellow
        500..=599 => "\x1b[31m", // red
        _ => "\x1b[35m",         // magenta
    }
}

fn format_duration(start: Instant) -> String {
    let duration = start.elapsed();
    format!("{:.2}ms", duration.as_secs_f64() * 1000.0)
}

fn request_path(req: &Request<Body>, show_query_string: bool) -> String {
    if show_query_string {
        return req
            .uri()
            .path_and_query()
            .map(|value| value.as_str().to_string())
            .unwrap_or_else(|| req.uri().path().to_string());
    }

    req.uri().path().to_string()
}

/// Main logging middleware for `axum::middleware::from_fn`.
///
/// ```ignore
/// use axlogger::{init_logger_config, logger_middleware};
/// use axum::{middleware, routing::get, Router};
///
/// #[tokio::main]
/// async fn main() {
///     init_logger_config("logger_config.toml");
///
///     let app = Router::new()
///         .route("/", get(|| async { "hello" }))
///         .layer(middleware::from_fn(logger_middleware));
/// }
/// ```
pub async fn logger_middleware(req: Request<Body>, next: Next) -> Response {
    let config = get_config();

    let method = req.method().clone();
    let path = request_path(&req, config.show_query_string);
    let start = Instant::now();

    let response = next.run(req).await;

    let status = response.status().as_u16();
    let duration = format_duration(start);

    let mut parts = Vec::new();

    if config.show_project_name {
        let project = format!("[{}]", config.project_name);

        parts.push(if config.colored {
            format!("{BOLD}{project}{RESET}")
        } else {
            project
        });
    }

    if config.show_method {
        parts.push(method.to_string());
    }

    if config.show_path {
        parts.push(path);
    }

    if config.show_status {
        parts.push(if config.colored {
            format!("{}{}{}", status_color(status), status, RESET)
        } else {
            status.to_string()
        });
    }

    if config.show_duration {
        parts.push(duration);
    }

    if config.show_timestamp {
        let timestamp = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();

        parts.push(if config.colored {
            format!("{DIM}{timestamp}{RESET}")
        } else {
            timestamp
        });
    }

    println!("{}", parts.join(" | "));

    response
}