Skip to main content

ngy_utils_tracing/
lib.rs

1//! # ngy-utils-tracing
2//!
3//! A logging initialization utility library built on [`tracing`], which automatically selects the
4//! log output based on the "application mode" ([`AppMode`]):
5//!
6//! - `Development`: Console logging to stderr (pretty format, with file name, line number and
7//!   thread ids)
8//! - `Test`: Console to stderr (pretty) + File (JSON)
9//! - `Production`: File logging (JSON; one file per day, named after the date in the configured
10//!   offset, see [`InitOptions::time_offset`])
11//!
12//! [`init`] performs one-time initialization of dotenv and tracing; repeated calls within the
13//! process return a clear error. After initialization, use [`get_current_mode`] to query the
14//! current mode.
15//!
16//! Every environment variable (log directory, application mode, timestamp offset, …) is read with
17//! the required prefix passed to [`InitOptions::new`], so an unrelated program that happens to use
18//! `LOG_DIR` or `APP_MODE` cannot change this crate's behaviour. `RUST_LOG` is the one exception:
19//! it keeps its unprefixed name because the whole Rust logging ecosystem shares it.
20//!
21//! See the [README](https://crates.io/crates/ngy-utils-tracing) for mode descriptions and the full API.
22
23use tracing_log::AsLog;
24
25mod app_mode;
26mod console_tracing;
27mod file_tracing;
28mod init;
29mod retention;
30mod rolling_file;
31mod test_tracing;
32mod timestamp;
33
34pub use app_mode::AppMode;
35pub use console_tracing::{build_debug_filter, console_tracing};
36pub use file_tracing::{
37    DEFAULT_LOG_DIR, DEFAULT_LOG_PREFIX, DEFAULT_MAX_LOG_FILES, build_file_filter, file_tracing,
38    resolve_log_dir, resolve_log_prefix, resolve_max_log_files,
39};
40pub use init::{InitOptions, InitResult, get_current_mode, init};
41pub use retention::cleanup_old_logs;
42pub use test_tracing::test_tracing;
43
44/// Build an environment variable name for `env_prefix`: `("NGY_", "LOG_DIR")` → `"NGY_LOG_DIR"`.
45///
46/// Every variable this crate reads goes through this helper except `RUST_LOG`, which keeps its
47/// unprefixed name because the whole Rust logging ecosystem shares it.
48pub(crate) fn env_var_name(env_prefix: &str, name: &str) -> String {
49    format!("{env_prefix}{name}")
50}
51
52/// Whether [`install_subscriber`] has installed our subscriber in this process.
53///
54/// Warning paths that can run either side of installation (the file writer, for one) need to know
55/// whether a `tracing` record reaches anybody: with a subscriber installed they use
56/// `tracing::warn!`, so the message lands in the log file `Production` mode relies on, and before
57/// that they fall back to stderr instead of being dropped silently.
58pub(crate) static SUBSCRIBER_INSTALLED: std::sync::atomic::AtomicBool =
59    std::sync::atomic::AtomicBool::new(false);
60
61/// Install `subscriber` as the process-wide default and, best effort, bridge `log` records into it.
62///
63/// A global subscriber that is already installed is a hard error: without ours, none of the
64/// logging configured here takes effect, so the caller must know. The `log` compatibility layer is
65/// different — an application may legitimately have installed a `log` logger (`env_logger`, …)
66/// before calling [`init`], so that case is reported on stderr and skipped rather than failing the
67/// whole initialization. This is why `SubscriberInitExt::try_init` is not used: it treats both
68/// cases as fatal.
69pub(crate) fn install_subscriber<S>(subscriber: S) -> anyhow::Result<()>
70where
71    S: tracing::Subscriber + Send + Sync + 'static,
72{
73    tracing::subscriber::set_global_default(subscriber).map_err(|err| {
74        anyhow::anyhow!(
75            "a global tracing subscriber is already installed, so the logging configuration of \
76             this crate cannot be applied: {err}"
77        )
78    })?;
79
80    // From here on a `tracing` record reaches the subscriber, so warning paths may switch from
81    // stderr to `tracing::warn!` (see `SUBSCRIBER_INSTALLED`).
82    SUBSCRIBER_INSTALLED.store(true, std::sync::atomic::Ordering::Relaxed);
83
84    // Same numeric level hint `try_init` would pass, so `log` records that the subscriber filters
85    // out are skipped as early as possible.
86    let max_level = tracing::level_filters::LevelFilter::current().as_log();
87    if let Err(err) = tracing_log::LogTracer::builder()
88        .with_max_level(max_level)
89        .init()
90    {
91        eprintln!(
92            "[WARN] a `log` logger is already installed, so `log` records will not be converted \
93             into tracing events: {err}"
94        );
95    }
96
97    Ok(())
98}
99
100/// Report a non-fatal problem in a code path that must not fail its caller.
101///
102/// Once [`install_subscriber`] has installed the subscriber the message goes through `tracing`,
103/// because in `Production` mode the log file is the only output and a warning printed to stderr
104/// would never reach it. Before that — a caller that never initialized tracing, or the cleanup that
105/// runs while a file layer is still being built — `tracing` would drop the record, so stderr is used
106/// instead of losing the warning silently.
107pub(crate) fn warn(message: std::fmt::Arguments<'_>) {
108    if SUBSCRIBER_INSTALLED.load(std::sync::atomic::Ordering::Relaxed) {
109        tracing::warn!("{}", message);
110    } else {
111        eprintln!("[WARN] {message}");
112    }
113}
114
115/// Default log level, applied when nothing more specific is configured.
116///
117/// [`build_debug_filter`] emits it as the fallback directive for crates that are neither listed in
118/// [`InitOptions::crates`] nor named by a `RUST_LOG` directive, and [`build_file_filter`] is called
119/// with it when [`file_tracing`] / [`test_tracing`] build the file layer.
120pub const DEFAULT_LOG_LEVEL: &str = "info";
121
122/// Last-resort UTC offset used for log timestamps, applied by both the console and the file layer.
123///
124/// An unconfigured offset follows the **machine's own time zone**; this constant only backs up a
125/// machine that cannot report one. [`InitOptions::time_offset`] wins, then the `LOG_TIME_OFFSET`
126/// environment variable (prefixed, see [`InitOptions::env_prefix`]), then the local zone, and this
127/// value is the last resort. The accepted forms are documented on [`InitOptions::time_offset`].
128pub const DEFAULT_TIME_OFFSET: &str = "UTC";
129
130// Test-only: serialize all environment variable access across the lib test binary to avoid
131// data races (unsafe) causing UB. The console_tracing, file_tracing and timestamp test modules all
132// use it.
133#[cfg(test)]
134pub(crate) static TEST_ENV_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());