Skip to main content

folk_core/
logging.rs

1//! `tracing` initialization.
2//!
3//! Three formats supported:
4//! - `text` — human-readable, single-line per event (default for terminals).
5//! - `json` — structured, one JSON object per line (for log aggregators).
6//! - `pretty` — multi-line human format (good for development).
7
8use anyhow::{Context, Result};
9use tracing_subscriber::{EnvFilter, fmt, prelude::*};
10
11use crate::config::{LogConfig, LogFormat};
12
13/// Initialize the global `tracing` subscriber.
14///
15/// Reads `RUST_LOG` first; if absent, uses `config.filter`.
16/// Format is selected by `config.format`.
17///
18/// Should be called exactly once at server startup. Calling twice is harmless
19/// but logs a warning.
20pub fn init(config: &LogConfig) -> Result<()> {
21    let filter =
22        EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(&config.filter));
23
24    let registry = tracing_subscriber::registry().with(filter);
25
26    let result = match config.format {
27        LogFormat::Text => registry.with(fmt::layer().with_target(true)).try_init(),
28        LogFormat::Json => registry.with(fmt::layer().json()).try_init(),
29        LogFormat::Pretty => registry.with(fmt::layer().pretty()).try_init(),
30    };
31
32    result.context("tracing subscriber already initialized")
33}