vulnera_advisor/
logging.rs

1//! Logging configuration and initialization.
2//!
3//! This module handles setting up the `tracing` subscriber, potentially directing
4//! logs to a file instead of stdout.
5
6use crate::config::Config;
7use tracing_appender::rolling;
8use tracing_subscriber::{EnvFilter, fmt, prelude::*};
9
10use tracing_appender::non_blocking::WorkerGuard;
11
12/// Initialize logging based on the provided configuration.
13///
14/// If `log_to_file` is enabled, logs will be written to daily files in `log_dir`.
15/// Otherwise, logs are written to stdout.
16///
17/// Returns an optional `WorkerGuard`. This guard MUST be held for the duration of the
18/// program (e.g., assigned to a variable in `main`). If dropped, log flushing may not complete.
19pub fn init_logging(config: &Config) -> Option<WorkerGuard> {
20    let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
21
22    if config.log_to_file {
23        // Create a rolling file appender that rotates daily
24        let file_appender = rolling::daily(&config.log_dir, "vulnera-advisor.log");
25        let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
26
27        tracing_subscriber::registry()
28            .with(env_filter)
29            .with(fmt::layer().with_writer(non_blocking).with_ansi(false))
30            .init();
31
32        Some(guard)
33    } else {
34        // Standard stdout logging
35        fmt()
36            .with_env_filter(env_filter)
37            .with_target(false) // Cleaner output for CLI
38            .init();
39
40        None
41    }
42}