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(
22            tracing_subscriber::EnvFilter::from_default_env()
23                .add_directive("synaps_cli=debug".parse().expect("valid directive"))
24                .add_directive("agent_core=debug".parse().expect("valid directive"))
25                .add_directive("agent_engine=debug".parse().expect("valid directive"))
26                .add_directive("agent_tui=debug".parse().expect("valid directive"))
27                .add_directive("tracing=info".parse().expect("valid directive")),
28        )
29        .with_writer(non_blocking)
30        .with_target(false)
31        .with_thread_ids(true)
32        .with_ansi(false)
33        .try_init()
34    {
35        eprintln!("Failed to initialize logging: {}", e);
36    }
37
38    Some(guard)
39}
40
41/// Default bounded-channel capacity for the non-blocking log writer.
42pub const DEFAULT_LOG_BUFFER_LINES: usize = 16_384;
43
44/// Buffer size for the non-blocking log writer: `SYNAPS_LOG_BUFFER_LINES`
45/// when set to a positive integer, otherwise [`DEFAULT_LOG_BUFFER_LINES`].
46pub fn log_buffer_lines() -> usize {
47    log_buffer_lines_from(std::env::var("SYNAPS_LOG_BUFFER_LINES").ok().as_deref())
48}
49
50fn log_buffer_lines_from(raw: Option<&str>) -> usize {
51    raw.and_then(|v| v.trim().parse::<usize>().ok())
52        .filter(|n| *n > 0)
53        .unwrap_or(DEFAULT_LOG_BUFFER_LINES)
54}
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59
60    #[test]
61    fn log_buffer_lines_honours_env_and_falls_back() {
62        assert_eq!(log_buffer_lines_from(None), DEFAULT_LOG_BUFFER_LINES);
63        assert_eq!(log_buffer_lines_from(Some("128000")), 128_000);
64        assert_eq!(log_buffer_lines_from(Some(" 42 ")), 42);
65        assert_eq!(log_buffer_lines_from(Some("0")), DEFAULT_LOG_BUFFER_LINES);
66        assert_eq!(
67            log_buffer_lines_from(Some("nope")),
68            DEFAULT_LOG_BUFFER_LINES
69        );
70    }
71}