Skip to main content

chess_tui/
logging.rs

1use chrono::Local;
2use log::LevelFilter;
3use simplelog::{CombinedLogger, Config, WriteLogger};
4use std::fs;
5use std::path::Path;
6
7/// Sets up logging for the application.
8///
9/// # Errors
10///
11/// Returns an error if:
12/// - The logs directory cannot be created
13/// - The log file cannot be created
14/// - The logger initialization fails
15pub fn setup_logging(
16    config_dir: &Path,
17    log_level: &LevelFilter,
18) -> Result<(), Box<dyn std::error::Error>> {
19    match log_level {
20        LevelFilter::Off => Ok(()), // No logging setup needed
21        level => {
22            // Create logs directory
23            let log_dir = config_dir.join("logs");
24            fs::create_dir_all(&log_dir)?;
25
26            // Create log file with timestamp
27            let timestamp = Local::now().format("%Y-%m-%d_%H-%M-%S");
28            let log_file = log_dir.join(format!("chess-tui_{timestamp}.log"));
29
30            CombinedLogger::init(vec![WriteLogger::new(
31                *level,
32                Config::default(),
33                fs::File::create(log_file)?,
34            )])?;
35
36            log::info!("Logging initialized at {level} level");
37            Ok(())
38        }
39    }
40}