Skip to main content

xet_runtime/logging/
init.rs

1#[cfg(not(target_family = "wasm"))]
2use std::ffi::OsStr;
3use std::io;
4use std::path::{Path, PathBuf};
5use std::sync::Mutex;
6#[cfg(not(target_family = "wasm"))]
7use std::sync::OnceLock;
8use std::thread::JoinHandle;
9use std::time::Duration;
10
11use chrono::{DateTime, FixedOffset, Local, Utc};
12use sysinfo::{Pid, ProcessRefreshKind, RefreshKind, System};
13use tracing::{debug, error, info, warn};
14#[cfg(not(target_family = "wasm"))]
15use tracing_appender::{non_blocking, rolling};
16use tracing_subscriber::layer::SubscriberExt;
17use tracing_subscriber::util::SubscriberInitExt;
18use tracing_subscriber::{EnvFilter, Layer};
19
20use super::config::*;
21use super::constants::DEFAULT_LOG_LEVEL_CONSOLE;
22#[cfg(not(target_family = "wasm"))]
23use super::constants::DEFAULT_LOG_LEVEL_FILE;
24use crate::error_printer::ErrorPrinter;
25use crate::utils::ByteSize;
26
27/// Global variable to hold the JoinHandle for the log cleanup thread
28static LOG_CLEANUP_HANDLE: Mutex<Option<JoinHandle<()>>> = Mutex::new(None);
29
30/// Wait for the log directory cleanup to complete.
31/// This function blocks until the background cleanup thread finishes.
32pub fn wait_for_log_directory_cleanup() {
33    if let Ok(mut handle_opt) = LOG_CLEANUP_HANDLE.lock()
34        && let Some(handle) = handle_opt.take()
35    {
36        let _ = handle.join();
37    }
38}
39
40/// The main entry point to set up logging.  Should only be called once.
41pub fn init(cfg: LoggingConfig) {
42    let mut dir_cleanup_task = None;
43
44    let maybe_log_file: Option<PathBuf> = {
45        match &cfg.logging_mode {
46            LoggingMode::Directory(log_dir) => {
47                if cfg.enable_log_dir_cleanup && log_dir.exists() && log_dir.is_dir() {
48                    dir_cleanup_task =
49                        Some(|| run_log_directory_cleanup_background(cfg.log_dir_config.clone(), log_dir));
50                }
51
52                Some(log_file_in_dir(&cfg.log_dir_config, log_dir))
53            },
54            LoggingMode::File(path_buf) => Some(path_buf.clone()),
55            LoggingMode::Console => None,
56        }
57    };
58
59    // Set up either logging to console or to a log file.
60    if let Some(log_file) = maybe_log_file {
61        // Attempt logging to a file, but fallback to console logging on error.
62        if let Err(e) = init_logging_to_file(&log_file, cfg.use_json) {
63            init_logging_to_console(&cfg);
64            error!("Error logging to file {log_file:?} ({e}); falling back to console logging.");
65        }
66    } else {
67        init_logging_to_console(&cfg);
68    }
69
70    // Log the version information.
71    info!("{}, xet-core revision {}", &cfg.version, git_version::git_version!(fallback = "unknown"));
72
73    if let Some(dir_cleanup_task_fn) = dir_cleanup_task {
74        dir_cleanup_task_fn();
75    }
76}
77
78fn init_logging_to_console(cfg: &LoggingConfig) {
79    // Now, just use basic console logging.
80    let registry = tracing_subscriber::registry();
81
82    #[cfg(feature = "tokio-console")]
83    let registry = {
84        // Console subscriber layer for tokio-console, custom filter for tokio trace level events
85        let console_layer = console_subscriber::spawn().with_filter(EnvFilter::new("tokio=trace,runtime=trace"));
86        registry.with(console_layer)
87    };
88
89    let fmt_layer_base = tracing_subscriber::fmt::layer()
90        .with_line_number(true)
91        .with_file(true)
92        .with_target(false);
93    let fmt_filter = EnvFilter::try_from_default_env()
94        .or_else(|_| EnvFilter::try_new(DEFAULT_LOG_LEVEL_CONSOLE))
95        .unwrap_or_default();
96
97    if cfg.use_json {
98        let filtered_fmt_layer = fmt_layer_base.json().with_filter(fmt_filter);
99        registry.with(filtered_fmt_layer).init();
100    } else {
101        let filtered_fmt_layer = fmt_layer_base.pretty().with_filter(fmt_filter);
102        registry.with(filtered_fmt_layer).init();
103    }
104}
105
106#[cfg(not(target_family = "wasm"))]
107fn init_logging_to_file(path: &Path, use_json: bool) -> Result<(), std::io::Error> {
108    // Set up logging to a file.
109    let (path, file_name) = match path.file_name() {
110        Some(name) => (path.to_path_buf(), name),
111        None => (path.join("xet.log"), OsStr::new("xet.log")),
112    };
113
114    let log_directory = match path.parent() {
115        Some(parent) => {
116            std::fs::create_dir_all(parent)?;
117            parent
118        },
119        None => Path::new("."),
120    };
121
122    // Make sure the log location is writeable so we error early here and dump to stderr on failure.
123    std::fs::write(&path, [])?;
124
125    // Build a non‑blocking file appender. • `rolling::never` = one static file, no rotation. • Keep the
126    // `WorkerGuard` alive so the background thread doesn’t shut down and drop messages.
127    let file_appender = rolling::never(log_directory, file_name);
128
129    let (writer, guard) = non_blocking(file_appender);
130
131    // Store the guard globally so it isn’t dropped.
132    static FILE_GUARD: OnceLock<tracing_appender::non_blocking::WorkerGuard> = OnceLock::new();
133    let _ = FILE_GUARD.set(guard); // ignore error if already initialised
134
135    let registry = tracing_subscriber::registry();
136
137    #[cfg(feature = "tokio-console")]
138    let registry = {
139        // Console subscriber layer for tokio-console, custom filter for tokio trace level events
140        let console_layer = console_subscriber::spawn().with_filter(EnvFilter::new("tokio=trace,runtime=trace"));
141        registry.with(console_layer)
142    };
143
144    // Build the fmt layer.
145    let fmt_layer_base = tracing_subscriber::fmt::layer()
146        .with_line_number(true)
147        .with_file(true)
148        .with_target(false)
149        .with_writer(writer);
150    // Standard filter layer: RUST_LOG env var or DEFAULT_LOG_LEVEL fallback.
151    let fmt_filter = EnvFilter::try_from_default_env()
152        .or_else(|_| EnvFilter::try_new(DEFAULT_LOG_LEVEL_FILE))
153        .unwrap_or_default();
154
155    if use_json {
156        registry.with(fmt_layer_base.json().with_filter(fmt_filter)).init();
157    } else {
158        registry.with(fmt_layer_base.pretty().with_filter(fmt_filter)).init();
159    };
160
161    Ok(())
162}
163
164#[cfg(target_family = "wasm")]
165fn init_logging_to_file(_path: &Path, _use_json: bool) -> Result<(), std::io::Error> {
166    Err(io::Error::new(io::ErrorKind::Unsupported, "file logging is not supported on wasm targets"))
167}
168
169/// Build `<prefix>_<YYYYMMDD>T<HHMMSS><mmm><+/-HHMM>_<pid>.log` in `dir`.
170/// Timestamp is in *local time with numeric offset* (e.g., -0700), filename-safe.
171pub fn log_file_in_dir(cfg: &LogDirConfig, dir: impl AsRef<Path>) -> PathBuf {
172    let now_local: DateTime<Local> = Local::now();
173    let now_fixed: DateTime<FixedOffset> = now_local.with_timezone(now_local.offset());
174
175    // ISO 8601 basic, filename-safe (no colons): 20250915T083210123-0700
176    let ts = now_fixed.format("%Y%m%dT%H%M%S%3f%z"); // %z => ±HHMM
177
178    let pid = std::process::id();
179    let prefix = &cfg.filename_prefix;
180    let filename = format!("{}_{}_{}.log", prefix, ts, pid);
181    dir.as_ref().join(filename)
182}
183
184/// Parse `<prefix>_<YYYYMMDD>T<HHMMSS><mmm><+/-HHMM>_<pid>.log`
185/// Works with full paths or bare filenames.
186/// Returns (prefix, timestamp with fixed offset, pid).
187pub fn parse_log_file_name(path: impl AsRef<Path>) -> Option<(String, DateTime<FixedOffset>, u32)> {
188    let path = path.as_ref();
189    let file_name = path.file_name()?.to_str()?;
190
191    // Returns None if it doesn't end with .log.
192    let file_name = file_name.strip_suffix(".log")?;
193
194    // Split from the RIGHT so base may contain underscores.
195    // Expect exactly: <base>_<timestamp>_<pid>
196    let mut parts = file_name.rsplitn(3, '_');
197    let pid_str = parts.next()?;
198    let ts_str = parts.next()?;
199    let prefix = parts.next()?; // remainder is the full base (may include underscores)
200
201    let pid: u32 = pid_str.parse().ok()?;
202
203    // Parse ISO 8601-basic with offset, no colons
204    let ts = DateTime::parse_from_str(ts_str, "%Y%m%dT%H%M%S%3f%z").ok()?;
205
206    Some((prefix.to_string(), ts, pid))
207}
208
209// A utility struct to help with the directory cleanup.
210struct CandidateLogFile {
211    path: PathBuf,
212    size: u64,
213    age: Duration,
214}
215
216/// Returns true if a running process with `pid` plausibly owns the log file named with
217/// `log_timestamp` (embedded in the filename at creation time).
218///
219/// PIDs are recycled on Windows and other OSes; [`System::process`] alone would treat a
220/// stale log file as protected whenever an unrelated process reuses the same PID. If the
221/// process start time is clearly after the log's embedded timestamp, the PID no longer
222/// refers to the process that created this file.
223fn pid_protects_log_file(sys: &System, pid: u32, log_timestamp: DateTime<FixedOffset>) -> bool {
224    let Some(proc) = sys.process(Pid::from_u32(pid)) else {
225        return false;
226    };
227    let log_epoch_secs = log_timestamp.timestamp();
228    let proc_start_secs = i64::try_from(proc.start_time()).unwrap_or(i64::MAX);
229    if proc_start_secs > log_epoch_secs {
230        debug!("PID {pid} likely reused: process start {proc_start_secs}s > log timestamp {log_epoch_secs}s");
231        return false;
232    }
233    true
234}
235
236fn run_log_directory_cleanup_background(cfg: LogDirConfig, log_dir: &Path) {
237    // Spawn run_log_directory_cleanup as background thread, logging any errors as a warn!
238    let log_dir = log_dir.to_path_buf();
239    let handle = std::thread::spawn(move || {
240        if let Err(e) = run_log_directory_cleanup(cfg, &log_dir) {
241            warn!("Error during log directory cleanup in {:?}: {}", log_dir, e);
242        }
243    });
244
245    // Store the JoinHandle in the global variable
246    if let Ok(mut handle_opt) = LOG_CLEANUP_HANDLE.lock() {
247        debug_assert!(handle_opt.is_none(), "Log directory cleanup called multiple times.");
248        *handle_opt = Some(handle);
249    }
250}
251
252fn run_log_directory_cleanup(cfg: LogDirConfig, log_dir: &Path) -> io::Result<()> {
253    info!(
254        "starting log cleanup in {:?} (min_age={:?}, max_retention={:?}, max_size={} bytes)",
255        log_dir,
256        cfg.min_deletion_age,
257        cfg.max_retention_age,
258        ByteSize::new(cfg.size_limit)
259    );
260
261    // Initialize sysinfo once to get a list of the active process ids.  To ensure we never delete
262    // a log file associated with an active process, we preserve any log file associated with a currently
263    // active PID.
264    let sys = System::new_with_specifics(RefreshKind::nothing().with_processes(ProcessRefreshKind::everything()));
265
266    // Collect candidate files.
267    let mut candidates = Vec::<CandidateLogFile>::new();
268    let mut total_bytes: u64 = 0;
269    let mut candidate_deletion_bytes: u64 = 0;
270
271    let now = Utc::now();
272    let mut n_log_files = 0usize;
273
274    for entry in std::fs::read_dir(log_dir)? {
275        let Ok(entry) = entry.warn_error_fn(|| format!("read_dir error while reading {log_dir:?}")) else {
276            continue;
277        };
278
279        let path = entry.path();
280
281        let Ok(ft) = entry.file_type() else { continue };
282        if !ft.is_file() {
283            continue;
284        }
285
286        let Some((prefix, timestamp, pid)) = parse_log_file_name(&path) else {
287            debug!("ignoring unparseable log file {:?}", path);
288            continue;
289        };
290
291        if prefix != cfg.filename_prefix {
292            debug!("ignoring log file {:?} with differing prefix {prefix} (!={})", path, &cfg.filename_prefix);
293            continue;
294        }
295
296        // Only use info here as it could be another process deleted it.
297        let Ok(meta) = entry
298            .metadata()
299            .info_error_fn(|| format!("Reading metadata failed for {:?}", path))
300        else {
301            continue;
302        };
303
304        let size = meta.len();
305        total_bytes += size;
306        n_log_files += 1;
307
308        let Ok(age) = (now - timestamp.to_utc()).to_std() else {
309            debug!("Skipping deletion for very new log file {path:?}");
310            continue;
311        };
312
313        // Skip if it's too new.
314        if age < cfg.min_deletion_age {
315            debug!("Skipping deletion for new log file {path:?}");
316            continue;
317        }
318
319        // Skip if there is an active PID associated with the file (and not PID reuse).
320        if pid_protects_log_file(&sys, pid, timestamp) {
321            debug!("Skipping deletion for log file {path:?} with active associated PID.");
322            continue;
323        }
324
325        // These files are available for deletion.
326        candidates.push(CandidateLogFile { path, size, age });
327
328        candidate_deletion_bytes += size;
329    }
330
331    info!(
332        "Log Directory Cleanup: found {:?} of logs in {} log files, with {:?} in {} files eligible for deletion.",
333        ByteSize::new(total_bytes),
334        n_log_files,
335        ByteSize::new(candidate_deletion_bytes),
336        candidates.len()
337    );
338
339    // 1) Hard expiration pass: delete anything older than max_retention, unless protected.
340    let mut deleted_bytes: u64 = 0;
341    candidates.retain(|lf| {
342        if lf.age > cfg.max_retention_age {
343            let path = &lf.path;
344            match std::fs::remove_file(path) {
345                Ok(_) => {
346                    deleted_bytes += lf.size;
347                    debug!("Log Directory Cleanup: Removed old log file {path:?})");
348                },
349                Err(e) => {
350                    // If the error is because the file no longer exists, then count it towards the deleted bytes;
351                    // otherwise log and skip.
352                    if e.kind() == io::ErrorKind::NotFound {
353                        deleted_bytes += lf.size;
354                        debug!("Log Directory Cleanup: Old log file {path:?} already deleted.");
355                    } else {
356                        info!("Log Directory Cleanup: Error removing old log file {path:?}, skipping: {e}");
357                    }
358                },
359            };
360            false
361        } else {
362            true
363        }
364    });
365
366    // 2) Size trimming: if above the limit, delete oldest eligible (unprotected) first.
367    let mut n_pruned = 0;
368    if total_bytes - deleted_bytes > cfg.size_limit {
369        // Sort by oldest first.
370        candidates.sort_by_key(|lf| std::cmp::Reverse(lf.age));
371        for lf in &candidates {
372            if total_bytes - deleted_bytes <= cfg.size_limit {
373                break;
374            }
375
376            match std::fs::remove_file(&lf.path) {
377                Ok(()) => {
378                    deleted_bytes += lf.size;
379                    n_pruned += 1;
380                    debug!("Log Directory cleanup: Pruned log file {:?}.", lf.path);
381                },
382                Err(e) => {
383                    if e.kind() == io::ErrorKind::NotFound {
384                        deleted_bytes += lf.size;
385                        n_pruned += 1;
386                        debug!("Log Directory cleanup: Log file {:?} already deleted, ignoring.", lf.path);
387                    } else {
388                        info!("Log Directory Cleanup: Error removing size-pruned log file {:?}: {}", lf.path, e);
389                    }
390                },
391            }
392        }
393    }
394
395    info!(
396        "Log Directory Cleanup: deleted {:?} in {} files",
397        ByteSize::new(deleted_bytes),
398        candidates.len() - n_pruned
399    );
400    Ok(())
401}
402
403#[cfg(test)]
404mod tests {
405
406    use chrono::{Datelike, Timelike};
407
408    use super::*;
409
410    #[test]
411    fn round_trip_make_and_parse() {
412        let dir = Path::new("/tmp");
413        let cfg = LogDirConfig::from_config(&crate::config::XetConfig::new());
414        let path = log_file_in_dir(&cfg, dir);
415        let (base, ts, pid) = parse_log_file_name(&path).expect("parse");
416        assert_eq!(base, cfg.filename_prefix);
417        assert!(pid > 0);
418
419        // Verify that the timestamp string matches what's embedded in the filename
420        let fname = path.file_name().unwrap().to_str().unwrap();
421        let ts_part = fname
422            .strip_prefix(&format!("{}_", base))
423            .unwrap()
424            .strip_suffix(&format!("_{}.log", pid))
425            .unwrap();
426        assert_eq!(ts_part, ts.format("%Y%m%dT%H%M%S%3f%z").to_string());
427    }
428
429    #[test]
430    fn parse_known_file() {
431        let fname = "app_base_20250915T083210123-0700_12345.log";
432        let (base, ts, pid) = parse_log_file_name(fname).expect("parse");
433        assert_eq!(base, "app_base");
434        assert_eq!(pid, 12345);
435        assert_eq!(ts.format("%Y%m%dT%H%M%S%3f%z").to_string(), "20250915T083210123-0700");
436        assert_eq!(ts.year(), 2025);
437        assert_eq!(ts.month(), 9);
438        assert_eq!(ts.day(), 15);
439        assert_eq!(ts.hour(), 8);
440        assert_eq!(ts.minute(), 32);
441        assert_eq!(ts.second(), 10);
442        assert_eq!(ts.timestamp_subsec_millis(), 123);
443        assert_eq!(ts.offset().local_minus_utc(), -7 * 3600);
444    }
445
446    #[test]
447    fn allows_underscores_in_base() {
448        let fname = "my_cool_app_20240102T030405006+0530_999.log";
449        let (base, ts, pid) = parse_log_file_name(fname).expect("parse");
450        assert_eq!(base, "my_cool_app");
451        assert_eq!(pid, 999);
452        assert_eq!(ts.format("%Y%m%dT%H%M%S%3f%z").to_string(), "20240102T030405006+0530");
453    }
454
455    #[test]
456    fn parse_with_directory_path() {
457        let path = Path::new("/var/log/myprog/app_20250915T083210123-0700_12345.log");
458        let (base, _, pid) = parse_log_file_name(path).expect("parse");
459        assert_eq!(base, "app");
460        assert_eq!(pid, 12345);
461    }
462}