Skip to main content

agent_core/core/
logging.rs

1use tracing_appender::non_blocking::WorkerGuard;
2
3pub fn init_logging() -> Option<WorkerGuard> {
4    let log_dir = crate::config::get_active_config_dir();
5    if !log_dir.exists() {
6        let _ = std::fs::create_dir_all(&log_dir);
7    }
8
9    let file_appender = tracing_appender::rolling::daily(log_dir, "synaps.log");
10    // `tracing_appender::non_blocking()` defaults to a 128 000-slot bounded
11    // channel whose slots are all touched at construction (~3.9 MiB of anon
12    // per process, forever). 16 k lines is far beyond any burst we have seen
13    // and the writer is lossy under backlog either way. Kill-switch:
14    // `SYNAPS_LOG_BUFFER_LINES=128000` restores the old buffer.
15    let (non_blocking, guard) = tracing_appender::non_blocking::NonBlockingBuilder::default()
16        .buffered_lines_limit(log_buffer_lines())
17        .lossy(true)
18        .finish(file_appender);
19
20    if let Err(e) = tracing_subscriber::fmt()
21        .with_env_filter(with_crate_directives(tracing_subscriber::EnvFilter::from_default_env()))
22        .with_writer(non_blocking)
23        .with_target(false)
24        .with_thread_ids(true)
25        .with_ansi(false)
26        .try_init()
27    {
28        eprintln!("Failed to initialize logging: {}", e);
29    }
30
31    Some(guard)
32}
33
34/// The log file's directives on top of `base` (the `RUST_LOG` filter, which
35/// is ERROR when unset): debug for Synaps's own crates. An event whose
36/// target is outside these crates is kept only at ERROR unless `RUST_LOG`
37/// says otherwise. Public so a test can check what reaches the log.
38pub fn with_crate_directives(base: tracing_subscriber::EnvFilter) -> tracing_subscriber::EnvFilter {
39    base.add_directive("synaps_cli=debug".parse().expect("valid directive"))
40        .add_directive("agent_core=debug".parse().expect("valid directive"))
41        .add_directive("agent_engine=debug".parse().expect("valid directive"))
42        .add_directive("agent_tui=debug".parse().expect("valid directive"))
43        .add_directive("tracing=info".parse().expect("valid directive"))
44}
45
46/// Default bounded-channel capacity for the non-blocking log writer.
47pub const DEFAULT_LOG_BUFFER_LINES: usize = 16_384;
48
49/// Buffer size for the non-blocking log writer: `SYNAPS_LOG_BUFFER_LINES`
50/// when set to a positive integer, otherwise [`DEFAULT_LOG_BUFFER_LINES`].
51pub fn log_buffer_lines() -> usize {
52    log_buffer_lines_from(std::env::var("SYNAPS_LOG_BUFFER_LINES").ok().as_deref())
53}
54
55fn log_buffer_lines_from(raw: Option<&str>) -> usize {
56    raw.and_then(|v| v.trim().parse::<usize>().ok())
57        .filter(|n| *n > 0)
58        .unwrap_or(DEFAULT_LOG_BUFFER_LINES)
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn log_buffer_lines_honours_env_and_falls_back() {
67        assert_eq!(log_buffer_lines_from(None), DEFAULT_LOG_BUFFER_LINES);
68        assert_eq!(log_buffer_lines_from(Some("128000")), 128_000);
69        assert_eq!(log_buffer_lines_from(Some(" 42 ")), 42);
70        assert_eq!(log_buffer_lines_from(Some("0")), DEFAULT_LOG_BUFFER_LINES);
71        assert_eq!(
72            log_buffer_lines_from(Some("nope")),
73            DEFAULT_LOG_BUFFER_LINES
74        );
75    }
76}