Skip to main content

sprite/utils/
logging.rs

1//! Logging infrastructure for the Sprite multi-agent workflow toolkit.
2//!
3//! This module provides logging functionality with support for different
4//! log levels, file output, and rotation.
5
6use crate::error::SpriteError;
7use anyhow::Result;
8use chrono::{DateTime, Local, Utc};
9use log::{Level, LevelFilter, Log, Metadata, Record};
10use std::fs::{File, OpenOptions};
11use std::io::{BufWriter, Write};
12use std::path::{Path, PathBuf};
13use std::sync::Mutex;
14
15/// Logger configuration.
16#[derive(Debug, Clone)]
17#[allow(dead_code)]
18pub struct LoggerConfig {
19    /// Log file path (None for stdout only)
20    pub log_file: Option<PathBuf>,
21    /// Log level
22    pub level: Level,
23    /// Whether to log to stdout
24    pub log_to_stdout: bool,
25    /// Whether to include timestamps
26    pub include_timestamp: bool,
27    /// Whether to include module names
28    pub include_module: bool,
29    /// Whether to use colors (for stdout)
30    pub use_colors: bool,
31}
32
33impl Default for LoggerConfig {
34    fn default() -> Self {
35        Self {
36            log_file: Some(PathBuf::from("logs/sprite.log")),
37            level: Level::Info,
38            log_to_stdout: true,
39            include_timestamp: true,
40            include_module: true,
41            use_colors: true,
42        }
43    }
44}
45
46/// A simple file and console logger for Sprite.
47#[allow(dead_code)]
48pub struct SpriteLogger {
49    config: LoggerConfig,
50    log_file: Option<Mutex<BufWriter<File>>>,
51    #[allow(dead_code)]
52    start_time: DateTime<Utc>,
53}
54
55impl SpriteLogger {
56    /// Create a new logger with the given configuration.
57    #[allow(dead_code)]
58    pub fn new(config: LoggerConfig) -> Result<Self> {
59        let log_file = if let Some(ref log_path) = config.log_file {
60            // Create parent directory if it doesn't exist
61            if let Some(parent) = log_path.parent() {
62                std::fs::create_dir_all(parent).map_err(|e| {
63                    SpriteError::filesystem_with_source(
64                        format!("Failed to create log directory: {}", e),
65                        parent.display().to_string(),
66                        e,
67                    )
68                })?;
69            }
70
71            let file = OpenOptions::new()
72                .create(true)
73                .append(true)
74                .open(log_path)
75                .map_err(|e| {
76                    SpriteError::filesystem_with_source(
77                        format!("Failed to open log file: {}", e),
78                        log_path.display().to_string(),
79                        e,
80                    )
81                })?;
82
83            Some(Mutex::new(BufWriter::new(file)))
84        } else {
85            None
86        };
87
88        Ok(Self {
89            config,
90            log_file,
91            start_time: Utc::now(),
92        })
93    }
94
95    /// Write a log entry.
96    #[allow(dead_code)]
97    fn write_log(&self, level: Level, record: &Record) {
98        let message = record.args().to_string();
99
100        let formatted = self.format_message(
101            level.to_level_filter(),
102            &message,
103            record.file(),
104            record.line(),
105        );
106
107        // Write to file if configured
108        if let Some(ref file_mutex) = self.log_file {
109            if let Ok(mut file) = file_mutex.lock() {
110                let _ = writeln!(file, "{}", formatted);
111                let _ = file.flush();
112            }
113        }
114
115        // Write to stdout if configured
116        if self.config.log_to_stdout {
117            eprintln!("{}", formatted);
118        }
119    }
120
121    /// Format a log message.
122    #[allow(dead_code)]
123    fn format_message(
124        &self,
125        level: LevelFilter,
126        message: &str,
127        file: Option<&str>,
128        line: Option<u32>,
129    ) -> String {
130        let mut parts = Vec::new();
131
132        // Add timestamp if configured
133        if self.config.include_timestamp {
134            parts.push(Local::now().format("%Y-%m-%d %H:%M:%S").to_string());
135        }
136
137        // Add log level with colors if configured
138        if self.config.use_colors {
139            let level_str = match level {
140                LevelFilter::Error => "\x1b[31mERROR\x1b[0m".to_string(),
141                LevelFilter::Warn => "\x1b[33mWARN \x1b[0m".to_string(),
142                LevelFilter::Info => "\x1b[32mINFO \x1b[0m".to_string(),
143                LevelFilter::Debug => "\x1b[36mDEBUG\x1b[0m".to_string(),
144                LevelFilter::Trace => "\x1b[37mTRACE\x1b[0m".to_string(),
145                _ => "UNKNOWN".to_string(),
146            };
147            parts.push(level_str);
148        } else {
149            let level_str = match level {
150                LevelFilter::Error => "ERROR".to_string(),
151                LevelFilter::Warn => "WARN ".to_string(),
152                LevelFilter::Info => "INFO ".to_string(),
153                LevelFilter::Debug => "DEBUG".to_string(),
154                LevelFilter::Trace => "TRACE".to_string(),
155                _ => "UNKNOWN".to_string(),
156            };
157            parts.push(level_str);
158        }
159
160        // Add module name if configured
161        if self.config.include_module {
162            if let Some(file) = file {
163                let module = file.rfind('/').map(|i| &file[i + 1..]).unwrap_or(file);
164                parts.push(format!("[{}]", module));
165            }
166        }
167
168        // Add line number if available
169        if let Some(line) = line {
170            parts.push(format!(":{}", line));
171        }
172
173        // Add the actual message
174        parts.push(message.to_string());
175
176        parts.join(" ")
177    }
178
179    /// Check if the given log level should be logged.
180    #[allow(dead_code)]
181    fn should_log(&self, level: LevelFilter) -> bool {
182        level <= self.config.level
183    }
184
185    /// Flush any buffered log data.
186    #[allow(dead_code)]
187    pub fn flush(&self) -> Result<()> {
188        if let Some(ref file_mutex) = self.log_file {
189            if let Ok(mut file) = file_mutex.lock() {
190                file.flush()?;
191            }
192        }
193        Ok(())
194    }
195
196    /// Get the logger start time.
197    #[allow(dead_code)]
198    pub fn start_time(&self) -> DateTime<Utc> {
199        self.start_time
200    }
201
202    /// Get the uptime since logger start.
203    #[allow(dead_code)]
204    pub fn uptime(&self) -> chrono::Duration {
205        Utc::now() - self.start_time
206    }
207}
208
209impl Log for SpriteLogger {
210    fn enabled(&self, metadata: &Metadata) -> bool {
211        self.should_log(metadata.level().to_level_filter())
212    }
213
214    fn log(&self, record: &Record) {
215        if self.should_log(record.level().to_level_filter()) {
216            self.write_log(record.level(), record);
217        }
218    }
219
220    fn flush(&self) {
221        let _ = self.flush();
222    }
223}
224
225/// Initialize logging for the application.
226#[allow(dead_code)]
227pub fn init_logging(config: LoggerConfig) -> Result<()> {
228    let logger = SpriteLogger::new(config)?;
229    let _ = log::set_boxed_logger(Box::new(logger));
230    Ok(())
231}
232
233/// Initialize logging with default configuration.
234#[allow(dead_code)]
235pub fn init_default_logging() -> Result<()> {
236    init_logging(LoggerConfig::default())
237}
238
239/// Initialize logging with a log file.
240#[allow(dead_code)]
241pub fn init_file_logging<P: AsRef<Path>>(log_file: P, level: Level) -> Result<()> {
242    let config = LoggerConfig {
243        log_file: Some(log_file.as_ref().to_path_buf()),
244        level,
245        log_to_stdout: true,
246        include_timestamp: true,
247        include_module: true,
248        use_colors: true,
249    };
250    init_logging(config)
251}
252
253/// Initialize logging without colors (for scripts).
254#[allow(dead_code)]
255pub fn init_script_logging<P: AsRef<Path>>(log_file: P, level: Level) -> Result<()> {
256    let config = LoggerConfig {
257        log_file: Some(log_file.as_ref().to_path_buf()),
258        level,
259        log_to_stdout: false,
260        include_timestamp: true,
261        include_module: false,
262        use_colors: false,
263    };
264    init_logging(config)
265}
266
267/// Get the current log level.
268#[allow(dead_code)]
269pub fn get_log_level() -> LevelFilter {
270    log::max_level()
271}
272
273/// Set the log level.
274#[allow(dead_code)]
275pub fn set_log_level(level: LevelFilter) {
276    log::set_max_level(level);
277}
278
279/// Create a log file with rotation support.
280#[allow(dead_code)]
281pub struct RotatingLogger {
282    config: LoggerConfig,
283    #[allow(dead_code)]
284    base_path: PathBuf,
285    #[allow(dead_code)]
286    current_file: PathBuf,
287    max_size: u64,
288    current_size: std::sync::atomic::AtomicU64,
289    file: Option<Mutex<BufWriter<File>>>,
290    #[allow(dead_code)]
291    start_time: DateTime<Utc>,
292}
293
294impl RotatingLogger {
295    /// Create a new rotating logger.
296    #[allow(dead_code)]
297    pub fn new<P: AsRef<Path>>(base_path: P, max_size: u64, level: Level) -> Result<Self> {
298        let base_path = base_path.as_ref().to_path_buf();
299        let current_file = base_path.join(format!("{}.log", Local::now().format("%Y%m%d_%H%M%S")));
300
301        let config = LoggerConfig {
302            log_file: Some(current_file.clone()),
303            level,
304            log_to_stdout: true,
305            include_timestamp: true,
306            include_module: true,
307            use_colors: true,
308        };
309
310        let file = Self::create_log_file(&current_file)?;
311        let current_size = Self::get_file_size(&current_file)?;
312
313        Ok(Self {
314            config,
315            base_path,
316            current_file,
317            max_size,
318            current_size: std::sync::atomic::AtomicU64::new(current_size),
319            file: Some(Mutex::new(BufWriter::new(file))),
320            start_time: Utc::now(),
321        })
322    }
323
324    /// Create the initial log file.
325    #[allow(dead_code)]
326    fn create_log_file(path: &Path) -> Result<File> {
327        // Create parent directory if needed
328        if let Some(parent) = path.parent() {
329            std::fs::create_dir_all(parent).map_err(|e| {
330                SpriteError::filesystem_with_source(
331                    format!("Failed to create log directory: {}", e),
332                    parent.display().to_string(),
333                    e,
334                )
335            })?;
336        }
337
338        Ok(OpenOptions::new()
339            .create(true)
340            .append(true)
341            .open(path)
342            .map_err(|e| {
343                SpriteError::filesystem_with_source(
344                    format!("Failed to create log file: {}", e),
345                    path.display().to_string(),
346                    e,
347                )
348            })?)
349    }
350
351    /// Get the size of a file.
352    #[allow(dead_code)]
353    fn get_file_size(path: &Path) -> Result<u64> {
354        let metadata = std::fs::metadata(path).map_err(|e| {
355            SpriteError::filesystem_with_source(
356                format!("Failed to get file size: {}", e),
357                path.display().to_string(),
358                e,
359            )
360        })?;
361        Ok(metadata.len())
362    }
363
364    /// Write a log entry with rotation.
365    #[allow(dead_code)]
366    fn write_log_with_rotation(&self, level: LevelFilter, record: &Record) {
367        let message = record.args().to_string();
368        let formatted = self.format_message(level, &message, record.file(), record.line());
369
370        // Check if we need to rotate
371        if self.current_size.load(std::sync::atomic::Ordering::Relaxed) >= self.max_size {
372            eprintln!("Log rotation needed but not implemented in this context");
373        }
374
375        // Write to current file
376        if let Some(ref file_mutex) = self.file {
377            if let Ok(mut file) = file_mutex.lock() {
378                let content = format!("{}\n", formatted);
379                if file.write(content.as_bytes()).is_ok() {
380                    // Note: actual size tracking would require getting the written bytes count
381                }
382                let _ = file.flush();
383            }
384        }
385
386        // Also write to stdout if configured
387        if self.config.log_to_stdout {
388            eprintln!("{}", formatted);
389        }
390    }
391
392    /// Rotate log files when they get too large.
393    #[allow(dead_code)]
394    fn rotate_files(&self) -> Result<()> {
395        // For now, just log that rotation is needed
396        eprintln!("Log rotation is needed but not fully implemented");
397        Ok(())
398    }
399
400    /// Clean up old log files.
401    #[allow(dead_code)]
402    fn cleanup_old_files(&self) -> Result<()> {
403        // List files matching the pattern
404        if let Ok(entries) = std::fs::read_dir(&self.base_path) {
405            let mut files: Vec<_> = entries
406                .filter_map(|entry| entry.ok())
407                .filter(|entry| {
408                    let binding = entry.file_name();
409                    let file_name = binding.to_string_lossy();
410                    file_name.ends_with(".log")
411                        && Some(file_name.as_ref())
412                            != self
413                                .current_file
414                                .file_name()
415                                .map(|n| n.to_string_lossy())
416                                .as_deref()
417                })
418                .collect();
419
420            // Sort by modification time (oldest first)
421            files.sort_by_key(|entry| {
422                entry
423                    .metadata()
424                    .and_then(|m| m.modified())
425                    .unwrap_or(std::time::SystemTime::UNIX_EPOCH)
426            });
427
428            // Keep only the last 5 files
429            if files.len() > 5 {
430                for old_file in &files[..files.len() - 5] {
431                    let _ = std::fs::remove_file(old_file.path());
432                    eprintln!("Removed old log file: {}", old_file.path().display());
433                }
434            }
435        }
436
437        Ok(())
438    }
439
440    /// Format a log message.
441    #[allow(dead_code)]
442    fn format_message(
443        &self,
444        level: LevelFilter,
445        message: &str,
446        file: Option<&str>,
447        line: Option<u32>,
448    ) -> String {
449        let mut parts = Vec::new();
450
451        if self.config.include_timestamp {
452            parts.push(Local::now().format("%Y-%m-%d %H:%M:%S").to_string());
453        }
454
455        let level_str = match level {
456            LevelFilter::Error => "\x1b[31mERROR\x1b[0m".to_string(),
457            LevelFilter::Warn => "\x1b[33mWARN \x1b[0m".to_string(),
458            LevelFilter::Info => "\x1b[32mINFO \x1b[0m".to_string(),
459            LevelFilter::Debug => "\x1b[36mDEBUG\x1b[0m".to_string(),
460            LevelFilter::Trace => "\x1b[37mTRACE\x1b[0m".to_string(),
461            _ => "UNKNOWN".to_string(),
462        };
463        parts.push(level_str);
464
465        if self.config.include_module {
466            if let Some(file) = file {
467                let module = file.rfind('/').map(|i| &file[i + 1..]).unwrap_or(file);
468                parts.push(format!("[{}]", module));
469            }
470        }
471
472        if let Some(line) = line {
473            parts.push(format!(":{}", line));
474        }
475
476        parts.push(message.to_string());
477
478        parts.join(" ")
479    }
480
481    /// Check if the given log level should be logged.
482    #[allow(dead_code)]
483    fn should_log(&self, level: LevelFilter) -> bool {
484        level <= self.config.level
485    }
486
487    /// Get the current log file path.
488    #[allow(dead_code)]
489    pub fn current_file(&self) -> &PathBuf {
490        &self.current_file
491    }
492
493    /// Get the logger start time.
494    #[allow(dead_code)]
495    pub fn start_time(&self) -> DateTime<Utc> {
496        self.start_time
497    }
498}
499
500impl Log for RotatingLogger {
501    fn enabled(&self, metadata: &Metadata) -> bool {
502        self.should_log(metadata.level().to_level_filter())
503    }
504
505    fn log(&self, record: &Record) {
506        if self.should_log(record.level().to_level_filter()) {
507            self.write_log_with_rotation(record.level().to_level_filter(), record);
508        }
509    }
510
511    fn flush(&self) {
512        if let Some(ref file_mutex) = self.file {
513            if let Ok(mut file) = file_mutex.lock() {
514                let _ = file.flush();
515            }
516        }
517    }
518}
519
520/// Initialize rotating logging.
521#[allow(dead_code)]
522pub fn init_rotating_logging<P: AsRef<Path>>(
523    log_dir: P,
524    max_size_mb: u64,
525    level: Level,
526) -> Result<()> {
527    let max_size_bytes = max_size_mb * 1024 * 1024;
528    let logger = RotatingLogger::new(log_dir, max_size_bytes, level)?;
529    let _ = log::set_boxed_logger(Box::new(logger));
530    Ok(())
531}
532
533/// Initialize rotating logging with default values.
534#[allow(dead_code)]
535pub fn init_default_rotating_logging() -> Result<()> {
536    init_rotating_logging("logs", 10, Level::Info)
537}
538
539#[cfg(test)]
540mod tests {
541    use super::*;
542    use tempfile::TempDir;
543
544    #[test]
545    fn test_logger_config_default() {
546        let config = LoggerConfig::default();
547        assert!(config.log_file.is_some());
548        assert_eq!(config.level, Level::Info);
549        assert!(config.log_to_stdout);
550        assert!(config.include_timestamp);
551        assert!(config.include_module);
552        assert!(config.use_colors);
553    }
554
555    #[test]
556    fn test_sprite_logger_creation() {
557        let config = LoggerConfig {
558            log_file: None,
559            level: Level::Debug,
560            log_to_stdout: false,
561            include_timestamp: false,
562            include_module: false,
563            use_colors: false,
564        };
565
566        let logger = SpriteLogger::new(config);
567        assert!(logger.is_ok());
568    }
569
570    #[test]
571    fn test_rotating_logger() {
572        let temp_dir = TempDir::new().unwrap();
573        let logger = RotatingLogger::new(temp_dir.path(), 100, Level::Info);
574        assert!(logger.is_ok());
575    }
576}