use axum::{body::Body, extract::Request, middleware::Next, response::Response};
use chrono::Local;
use serde::Deserialize;
use std::{sync::OnceLock, time::Instant};
#[derive(Debug, Deserialize, Clone)]
pub struct LoggerConfig {
#[serde(default = "default_project_name")]
pub project_name: String,
#[serde(default = "default_true")]
pub show_project_name: bool,
#[serde(default = "default_true")]
pub show_method: bool,
#[serde(default = "default_true")]
pub show_path: bool,
#[serde(default = "default_true")]
pub show_status: bool,
#[serde(default = "default_true")]
pub show_duration: bool,
#[serde(default = "default_true")]
pub show_timestamp: bool,
#[serde(default)]
pub show_query_string: bool,
#[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();
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(),
};
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", 200..=299 => "\x1b[32m", 300..=399 => "\x1b[36m", 400..=499 => "\x1b[33m", 500..=599 => "\x1b[31m", _ => "\x1b[35m", }
}
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()
}
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
}