tracing_setup/
init_file_logging.rs

1crate::ix!();
2
3pub fn init_default_file_logging() {
4    let config = FileLoggingConfiguration::default();
5    init_file_logging(config);
6}
7
8pub fn create_file_logging_subscriber(config: &FileLoggingConfiguration) -> impl Subscriber + Send + Sync {
9    let writer = config.create_writer();
10
11    let env_filter = std::env::var("LOGFLAG").unwrap_or_else(|_| "info".to_string());
12
13    FmtSubscriber::builder()
14        .with_max_level(*config.log_level())
15        .with_env_filter(EnvFilter::new(env_filter))
16        .with_writer(writer)
17        .finish()
18}
19
20pub fn init_file_logging(config: FileLoggingConfiguration) {
21    static INIT: std::sync::Once = std::sync::Once::new();
22    static GUARD: Mutex<Option<tracing::subscriber::DefaultGuard>> = Mutex::new(None);
23
24    INIT.call_once(|| {
25        // Create the subscriber
26        let subscriber = create_file_logging_subscriber(&config);
27
28        if tracing::subscriber::set_global_default(subscriber).is_err() {
29            eprintln!("Global subscriber already set, proceeding without setting it again.");
30
31            // Re-create the subscriber since the previous one was moved
32            let subscriber = create_file_logging_subscriber(&config);
33
34            // Set the subscriber for the current thread
35            let guard = tracing::subscriber::set_default(subscriber);
36            *GUARD.lock().unwrap() = Some(guard);
37            // The guard is stored in a Mutex to keep it alive
38        } else {
39            tracing::info!("Logging initialized with file rotation");
40        }
41    });
42}
43
44#[cfg(test)]
45mod file_logging_tests {
46    use super::*;
47    use std::fs;
48    use std::path::PathBuf;
49    use tracing_subscriber::fmt::MakeWriter;
50
51    #[test]
52    #[serial]
53    fn test_create_writer_with_rotation() {
54        let log_file = PathBuf::from("test_rotation.log");
55        let config = FileLoggingConfiguration::new_temporary(
56            Some(log_file.clone()),
57            Level::DEBUG,
58            Some(Rotation::DAILY),
59        );
60
61        let subscriber = create_file_logging_subscriber(&config);
62
63        tracing::subscriber::with_default(subscriber, || {
64            // Log some messages
65            tracing::debug!("This is a test debug message");
66        });
67
68        // Clean up
69        config.remove_logs();
70    }
71
72    #[test]
73    #[serial]
74    fn test_create_writer_without_rotation() {
75        let log_file = PathBuf::from("test_no_rotation.log");
76        let config = FileLoggingConfiguration::new_temporary(
77            Some(log_file.clone()),
78            Level::DEBUG,
79            None,
80        );
81        let writer = config.create_writer();
82        // Verify the writer is created successfully
83        let _ = writer.make_writer();
84
85        // Clean up
86        config.remove_logs();
87    }
88
89    #[test]
90    #[serial]
91    fn test_default_logging_configuration() {
92        let config = FileLoggingConfiguration::default_temporary();
93        assert!(config.log_path_root_is("default.log"));
94        assert!(config.info_level());
95        assert!(config.rotates_daily());
96    }
97
98    #[test]
99    #[serial]
100    fn test_init_file_logging_with_defaults() {
101        use chrono::Local;
102        use std::fs;
103
104        let config = FileLoggingConfiguration::default();
105        let subscriber = create_file_logging_subscriber(&config);
106
107        tracing::subscriber::with_default(subscriber, || {
108            tracing::info!("This is a default log message.");
109            tracing::debug!("This is a debug message, but won't appear with default level.");
110
111            // Wait briefly to ensure the log is written
112            std::thread::sleep(std::time::Duration::from_millis(100));
113
114            // Determine the log file name with the date suffix
115            let date_suffix = Local::now().format("%Y-%m-%d").to_string();
116            let log_file_name = format!("default.log.{}", date_suffix);
117
118            // Read the log file
119            let log_contents = fs::read_to_string(&log_file_name).expect("Failed to read log file");
120            assert!(log_contents.contains("This is a default log message."));
121            assert!(!log_contents.contains("This is a debug message"));
122
123            // Clean up
124            let _ = fs::remove_file(log_file_name);
125        });
126    }
127}