Skip to main content

commons/
logging.rs

1//! Structured logging and telemetry utilities.
2
3use std::fmt;
4
5/// Log levels for structured logging
6#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
7pub enum LogLevel {
8    /// Trace level - very verbose debugging
9    Trace = 0,
10    /// Debug level - debugging information
11    Debug = 1,
12    /// Info level - general information
13    Info = 2,
14    /// Warn level - warning messages
15    Warn = 3,
16    /// Error level - error messages
17    Error = 4,
18}
19
20impl fmt::Display for LogLevel {
21    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22        match self {
23            LogLevel::Trace => write!(f, "TRACE"),
24            LogLevel::Debug => write!(f, "DEBUG"),
25            LogLevel::Info => write!(f, "INFO"),
26            LogLevel::Warn => write!(f, "WARN"),
27            LogLevel::Error => write!(f, "ERROR"),
28        }
29    }
30}
31
32/// Simple structured logger
33#[derive(Debug)]
34pub struct Logger {
35    level: LogLevel,
36    module: String,
37}
38
39impl Logger {
40    /// Create a new logger for a module
41    pub fn new(module: &str) -> Self {
42        Self {
43            level: LogLevel::Info,
44            module: module.to_string(),
45        }
46    }
47
48    /// Set the minimum log level
49    pub fn set_level(&mut self, level: LogLevel) {
50        self.level = level;
51    }
52
53    /// Log a message at the given level
54    pub fn log(&self, level: LogLevel, message: &str) {
55        if level >= self.level {
56            let timestamp = crate::time::unix_timestamp();
57            println!("[{}] {} [{}] {}", timestamp, level, self.module, message);
58        }
59    }
60
61    /// Log a trace message
62    pub fn trace(&self, message: &str) {
63        self.log(LogLevel::Trace, message);
64    }
65
66    /// Log a debug message
67    pub fn debug(&self, message: &str) {
68        self.log(LogLevel::Debug, message);
69    }
70
71    /// Log an info message
72    pub fn info(&self, message: &str) {
73        self.log(LogLevel::Info, message);
74    }
75
76    /// Log a warning message
77    pub fn warn(&self, message: &str) {
78        self.log(LogLevel::Warn, message);
79    }
80
81    /// Log an error message
82    pub fn error(&self, message: &str) {
83        self.log(LogLevel::Error, message);
84    }
85}
86
87/// Create a logger for the current module
88#[macro_export]
89macro_rules! logger {
90    () => {
91        $crate::logging::Logger::new(module_path!())
92    };
93}