Skip to main content

rs_zero/core/
logging.rs

1//! Logging configuration and helpers.
2
3pub mod aggregation;
4pub mod config;
5pub mod fields;
6pub(crate) mod format;
7pub mod redaction;
8pub(crate) mod rotation;
9pub mod sampling;
10pub mod writer;
11
12use std::sync::{Mutex, OnceLock};
13
14use tracing_appender::non_blocking::WorkerGuard;
15use tracing_subscriber::{
16    EnvFilter,
17    fmt::{
18        self,
19        format::{DefaultFields, FmtSpan, Format},
20        writer::BoxMakeWriter,
21    },
22    layer::SubscriberExt,
23    util::SubscriberInitExt,
24};
25
26use crate::core::{CoreError, CoreResult};
27
28pub use aggregation::{ErrorAggregationSnapshot, ErrorAggregator, ErrorGroup};
29pub use config::{LogConfig, LogFormat, LogSpanEvents};
30pub use fields::LogFields;
31use format::{RedactingJsonFields, RedactingJsonFormat, RedactingTextFormat};
32pub use redaction::{RedactionConfig, redact_text};
33pub use sampling::{LogSampler, SamplingConfig};
34pub use writer::{
35    LogWriterConfig, PreparedLogWriter, RollingFileConfig, RotationPolicy,
36    RuntimeRollingFileWriter, validate_writer,
37};
38
39static LOG_WORKER_GUARDS: OnceLock<Mutex<Vec<WorkerGuard>>> = OnceLock::new();
40
41/// Guard that keeps non-blocking log workers alive until dropped.
42#[derive(Default)]
43pub struct TracingGuard {
44    guards: Vec<WorkerGuard>,
45}
46
47/// Initializes a global tracing subscriber.
48///
49/// Calling this more than once returns `CoreError::SubscriberInit`; tests can
50/// use `try_init` semantics by ignoring that specific error.
51///
52/// File-backed non-blocking logs should prefer [`init_tracing_with_guard`] so
53/// the returned guard can flush buffered records during normal shutdown.
54pub fn init_tracing(config: LogConfig) -> CoreResult<()> {
55    let (subscriber, guard) = build_subscriber(config)?;
56    subscriber
57        .try_init()
58        .map_err(|_| CoreError::SubscriberInit)?;
59    retain_global_guard(guard)?;
60    Ok(())
61}
62
63/// Initializes global tracing and returns a guard for non-blocking log workers.
64pub fn init_tracing_with_guard(config: LogConfig) -> CoreResult<TracingGuard> {
65    let (subscriber, guard) = build_subscriber(config)?;
66    subscriber
67        .try_init()
68        .map_err(|_| CoreError::SubscriberInit)?;
69    Ok(guard)
70}
71
72/// Runs a closure with a scoped tracing subscriber.
73///
74/// This is primarily useful for tests and embedded runtimes that need isolated
75/// logging without installing a process-global subscriber.
76pub fn with_scoped_tracing<T>(config: LogConfig, run: impl FnOnce() -> T) -> CoreResult<T> {
77    let (subscriber, worker_guard) = build_subscriber(config)?;
78    let guard = subscriber.set_default();
79    let result = run();
80    drop(guard);
81    drop(worker_guard);
82    Ok(result)
83}
84
85fn build_subscriber(config: LogConfig) -> CoreResult<(tracing::Dispatch, TracingGuard)> {
86    let filter =
87        EnvFilter::try_new(config.filter.clone()).unwrap_or_else(|_| EnvFilter::new("info"));
88    let span_events = span_events(config.span_events);
89    let (writer, guard) = build_writer(&config.writer)?;
90
91    let dispatch = match config.format {
92        LogFormat::Text => build_text_subscriber(config, filter, span_events, writer),
93        LogFormat::Json => build_json_subscriber(config, filter, span_events, writer),
94    }?;
95    Ok((dispatch, guard))
96}
97
98fn build_text_subscriber(
99    config: LogConfig,
100    filter: EnvFilter,
101    span_events: FmtSpan,
102    writer: BoxMakeWriter,
103) -> CoreResult<tracing::Dispatch> {
104    let formatter = Format::default()
105        .with_ansi(config.ansi)
106        .with_target(config.with_target);
107    let layer = fmt::layer()
108        .event_format(RedactingTextFormat::new(
109            formatter,
110            config.redaction.clone(),
111        ))
112        .fmt_fields(DefaultFields::new())
113        .with_writer(writer);
114    let mut layer = layer;
115    layer.set_span_events(span_events);
116    Ok(tracing::Dispatch::new(
117        tracing_subscriber::registry().with(layer).with(filter),
118    ))
119}
120
121fn build_json_subscriber(
122    config: LogConfig,
123    filter: EnvFilter,
124    span_events: FmtSpan,
125    writer: BoxMakeWriter,
126) -> CoreResult<tracing::Dispatch> {
127    let formatter = Format::default()
128        .json()
129        .with_ansi(false)
130        .with_target(config.with_target)
131        .with_current_span(config.include_current_span)
132        .with_span_list(config.include_span_list);
133
134    let layer = fmt::layer()
135        .fmt_fields(RedactingJsonFields::new(config.redaction.clone()))
136        .event_format(RedactingJsonFormat::new(
137            formatter,
138            config.redaction.clone(),
139        ))
140        .with_writer(writer);
141    let mut layer = layer;
142    layer.set_span_events(span_events);
143    Ok(tracing::Dispatch::new(
144        tracing_subscriber::registry().with(layer).with(filter),
145    ))
146}
147
148fn build_writer(config: &LogWriterConfig) -> CoreResult<(BoxMakeWriter, TracingGuard)> {
149    validate_writer(config)?;
150    match config {
151        LogWriterConfig::Stdout => {
152            Ok((BoxMakeWriter::new(std::io::stdout), TracingGuard::default()))
153        }
154        LogWriterConfig::Stderr => {
155            Ok((BoxMakeWriter::new(std::io::stderr), TracingGuard::default()))
156        }
157        LogWriterConfig::File(path) => {
158            let file = writer::open_append_file(path)?;
159            Ok((
160                BoxMakeWriter::new(move || file.try_clone().expect("clone log file")),
161                TracingGuard::default(),
162            ))
163        }
164        LogWriterConfig::RollingFile(rolling) => {
165            let writer = RuntimeRollingFileWriter::new(rolling.clone())?;
166            let (writer, guard) = tracing_appender::non_blocking(writer);
167            Ok((
168                BoxMakeWriter::new(move || writer.clone()),
169                TracingGuard {
170                    guards: vec![guard],
171                },
172            ))
173        }
174    }
175}
176
177fn retain_global_guard(mut guard: TracingGuard) -> CoreResult<()> {
178    if guard.guards.is_empty() {
179        return Ok(());
180    }
181    let mut guards = LOG_WORKER_GUARDS
182        .get_or_init(|| Mutex::new(Vec::new()))
183        .lock()
184        .map_err(|_| CoreError::Logging("log worker guard mutex poisoned".to_string()))?;
185    guards.append(&mut guard.guards);
186    Ok(())
187}
188
189#[cfg(test)]
190pub mod test_hooks {
191    use std::{
192        path::{Path, PathBuf},
193        sync::{
194            Arc, Condvar, Mutex,
195            atomic::{AtomicI32, AtomicU64, Ordering},
196        },
197    };
198
199    static CURRENT_DAY_OFFSET: AtomicI32 = AtomicI32::new(0);
200    static NEXT_PAUSE_ID: AtomicU64 = AtomicU64::new(1);
201    static COMPRESSION_PAUSE: Mutex<Option<Arc<CompressionPauseState>>> = Mutex::new(None);
202
203    struct CompressionPauseState {
204        id: u64,
205        dir: PathBuf,
206        released: Mutex<bool>,
207        condvar: Condvar,
208    }
209
210    pub struct CompressionPause {
211        state: Arc<CompressionPauseState>,
212    }
213
214    impl CompressionPause {
215        pub fn resume(self) {
216            self.state.resume();
217        }
218    }
219
220    impl Drop for CompressionPause {
221        fn drop(&mut self) {
222            self.state.resume();
223            clear_pause(self.state.id);
224        }
225    }
226
227    impl CompressionPauseState {
228        fn resume(&self) {
229            let mut released = self.released.lock().expect("compression pause mutex");
230            *released = true;
231            self.condvar.notify_all();
232        }
233    }
234
235    pub struct CurrentDayOffsetGuard {
236        previous: i32,
237    }
238
239    impl CurrentDayOffsetGuard {
240        pub fn set_offset_days(&self, days: i32) {
241            CURRENT_DAY_OFFSET.store(days, Ordering::SeqCst);
242        }
243    }
244
245    impl Drop for CurrentDayOffsetGuard {
246        fn drop(&mut self) {
247            CURRENT_DAY_OFFSET.store(self.previous, Ordering::SeqCst);
248        }
249    }
250
251    pub fn pause_compression_for_dir(dir: &Path) -> CompressionPause {
252        let state = Arc::new(CompressionPauseState {
253            id: NEXT_PAUSE_ID.fetch_add(1, Ordering::SeqCst),
254            dir: dir.to_path_buf(),
255            released: Mutex::new(false),
256            condvar: Condvar::new(),
257        });
258        *COMPRESSION_PAUSE.lock().expect("compression pause mutex") = Some(state.clone());
259        CompressionPause { state }
260    }
261
262    pub fn set_current_day_offset(days: i32) -> CurrentDayOffsetGuard {
263        let previous = CURRENT_DAY_OFFSET.swap(days, Ordering::SeqCst);
264        CurrentDayOffsetGuard { previous }
265    }
266
267    pub(crate) fn current_day_offset() -> i32 {
268        CURRENT_DAY_OFFSET.load(Ordering::SeqCst)
269    }
270
271    pub(crate) fn pause_if_configured(path: &Path) {
272        let Some(state) = COMPRESSION_PAUSE
273            .lock()
274            .expect("compression pause mutex")
275            .clone()
276        else {
277            return;
278        };
279        if path.parent() != Some(state.dir.as_path()) {
280            return;
281        }
282        let mut released = state.released.lock().expect("compression pause mutex");
283        while !*released {
284            released = state
285                .condvar
286                .wait(released)
287                .expect("compression pause condvar");
288        }
289    }
290
291    fn clear_pause(id: u64) {
292        let mut pause = COMPRESSION_PAUSE.lock().expect("compression pause mutex");
293        if pause.as_ref().is_some_and(|state| state.id == id) {
294            *pause = None;
295        }
296    }
297}
298
299fn span_events(events: LogSpanEvents) -> FmtSpan {
300    match events {
301        LogSpanEvents::None => FmtSpan::NONE,
302        LogSpanEvents::Close => FmtSpan::CLOSE,
303        LogSpanEvents::NewAndClose => FmtSpan::NEW | FmtSpan::CLOSE,
304        LogSpanEvents::Full => FmtSpan::FULL,
305    }
306}
307
308#[cfg(test)]
309mod tests {
310    use super::{LogConfig, init_tracing};
311
312    #[test]
313    fn init_tracing_is_callable() {
314        let _ = init_tracing(LogConfig {
315            filter: "debug".to_string(),
316            ansi: false,
317            ..LogConfig::default()
318        });
319    }
320}