Skip to main content

sqlite_graphrag/
tracing_init.rs

1//! Centralized tracing subscriber initialization.
2//!
3//! Configures the global subscriber with JSON or pretty format,
4//! installs the panic hook and the log-to-tracing bridge.
5//!
6//! GAP-SG-99 / GAP-SG-108: when XDG `log.to_file` is truthy, also write a
7//! rolling file under the cache dir via `tracing-appender`. The returned
8//! [`WorkerGuard`] MUST be held until process exit so buffers flush.
9
10use std::sync::Mutex;
11
12use tracing_appender::non_blocking::WorkerGuard;
13use tracing_subscriber::EnvFilter;
14
15/// Process-wide guard so the non-blocking appender flushes on drop.
16///
17/// Held in a static so the signal handler (and early `process::exit` paths)
18/// can still flush without access to `main` stack frames. Prefer
19/// [`flush_tracing`] over bare `process::exit` without a prior flush
20/// (tracing-appender WorkerGuard docs: abrupt exit may lose buffered lines).
21static FILE_GUARD: Mutex<Option<WorkerGuard>> = Mutex::new(None);
22
23/// Initializes the global tracing subscriber, panic hook, and log bridge.
24///
25/// Must be called exactly once, before any tracing events are emitted.
26/// After this call, panics on any thread produce `tracing::error!` events,
27/// and `log` crate events from dependencies (refinery, ureq, ort) are
28/// forwarded to the tracing subscriber.
29///
30/// Stderr is always the agent-facing diagnostic stream. File logging is
31/// optional via XDG `log.to_file` (GAP-SG-108).
32pub fn init_tracing(log_level: &str, log_format: &str) {
33    // TR02: the log→tracing bridge is activated automatically by
34    // tracing-subscriber's built-in `tracing-log` feature (default).
35    // Calling LogTracer::init() separately would conflict with the
36    // global logger that tracing-subscriber installs via .init().
37    let use_ansi = crate::terminal::should_use_ansi();
38    let to_file = crate::config::get_setting("log.to_file")
39        .ok()
40        .flatten()
41        .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
42        .unwrap_or(false);
43
44    let file_writer = if to_file {
45        let dir = crate::paths::cache_dir()
46            .unwrap_or_else(|_| std::env::temp_dir().join("sqlite-graphrag"));
47        let log_dir = dir.join("logs");
48        let _ = std::fs::create_dir_all(&log_dir);
49        let rotation = crate::config::get_setting("log.rotation")
50            .ok()
51            .flatten()
52            .unwrap_or_else(|| "daily".into());
53        let appender = match rotation.as_str() {
54            "hourly" => tracing_appender::rolling::hourly(&log_dir, "sqlite-graphrag.log"),
55            "never" => tracing_appender::rolling::never(&log_dir, "sqlite-graphrag.log"),
56            _ => tracing_appender::rolling::daily(&log_dir, "sqlite-graphrag.log"),
57        };
58        let (non_blocking, guard) = tracing_appender::non_blocking(appender);
59        if let Ok(mut slot) = FILE_GUARD.lock() {
60            *slot = Some(guard);
61        }
62        Some(non_blocking)
63    } else {
64        None
65    };
66
67    // Always write diagnostics to stderr (agent-native). Optionally tee to file.
68    if let Some(nb) = file_writer {
69        use tracing_subscriber::fmt::writer::MakeWriterExt;
70        let writer = std::io::stderr.and(nb);
71        if log_format == "json" {
72            tracing_subscriber::fmt()
73                .json()
74                .with_ansi(false)
75                .with_thread_ids(true)
76                .with_thread_names(true)
77                .with_env_filter(EnvFilter::new(log_level))
78                .with_writer(writer)
79                .init();
80        } else {
81            tracing_subscriber::fmt()
82                .with_ansi(use_ansi)
83                .with_env_filter(EnvFilter::new(log_level))
84                .with_writer(writer)
85                .init();
86        }
87    } else if log_format == "json" {
88        tracing_subscriber::fmt()
89            .json()
90            .with_ansi(false)
91            .with_thread_ids(true)
92            .with_thread_names(true)
93            .with_env_filter(EnvFilter::new(log_level))
94            .with_writer(std::io::stderr)
95            .init();
96    } else {
97        tracing_subscriber::fmt()
98            .with_ansi(use_ansi)
99            .with_env_filter(EnvFilter::new(log_level))
100            .with_writer(std::io::stderr)
101            .init();
102    }
103
104    // TR05: confirm effective filter after init
105    tracing::debug!(
106        target: "logging",
107        filter = %log_level,
108        format = %log_format,
109        ansi = use_ansi,
110        to_file,
111        "tracing subscriber initialized (local only; no remote telemetry)"
112    );
113
114    // TR01 (v1.0.80, A1/G2): panic hook emits a structured tracing::error!
115    // and DELIBERATELY DOES NOT call the previous hook. The default Rust
116    // panic hook prints the same payload + location to stderr; combined
117    // with the tracing event below, that produces a double-trace (one
118    // structured event in JSON or pretty, one unstructured dump). We
119    // prefer the structured single-trace: the tracing event carries the
120    // same payload and location fields and is captured by the global
121    // subscriber. Test runs still fail on panic because Rust aborts the
122    // process regardless of which hook is installed.
123    std::panic::set_hook(Box::new(|info| {
124        let payload = info
125            .payload()
126            .downcast_ref::<&str>()
127            .copied()
128            .or_else(|| info.payload().downcast_ref::<String>().map(|s| s.as_str()))
129            .unwrap_or("<non-string panic>");
130        let location = info
131            .location()
132            .map(|l| format!("{}:{}:{}", l.file(), l.line(), l.column()));
133        tracing::error!(
134            target: "panic",
135            message = %payload,
136            location = location.as_deref().unwrap_or("unknown"),
137            "thread panicked"
138        );
139    }));
140}
141
142/// Drop the file-appender worker so buffered events flush (GAP-SG-99).
143///
144/// Safe to call multiple times. Invoked from the second-signal path before
145/// `process::exit` and at the end of a normal `main` return when possible.
146pub fn flush_tracing() {
147    if let Ok(mut slot) = FILE_GUARD.lock() {
148        *slot = None;
149    }
150}