Skip to main content

easypdf_core/
logging.rs

1//! 可观测性初始化与日志工具。
2//!
3//! 提供两种订阅者模式:
4//!
5//! - [`init_logging`]: 紧凑的人类可读输出到 stderr(开发环境)。
6//! - [`init_logging_json`]: 结构化 JSON 输出到 stderr(生产环境)。
7//!
8//! 两者均读取 `RUST_LOG` 环境变量来控制过滤级别。
9//! 语法参见 [`tracing_subscriber::EnvFilter`]。
10//!
11//! # Examples
12//!
13//! ```rust
14//! // 在应用入口点中:
15//! easypdf_core::logging::init_logging().ok();
16//! tracing::info!("application started");
17//! ```
18
19use tracing_subscriber::EnvFilter;
20
21/// 使用紧凑的人类可读输出初始化全局 tracing 订阅者。
22///
23/// 适用于开发环境。读取 `RUST_LOG` 进行级别过滤
24///(未设置时默认为 `info`)。输出到 stderr。
25///
26/// # Errors
27///
28/// 全局订阅者已被设置时返回错误
29///(例如之前已调用 `init_logging` 或 `init_logging_json`)。
30pub fn init_logging() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
31    tracing_subscriber::fmt()
32        .with_env_filter(
33            EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")),
34        )
35        .with_target(false)
36        .compact()
37        .try_init()
38}
39
40/// 使用结构化 JSON 输出初始化全局 tracing 订阅者。
41///
42/// 适用于生产环境。读取 `RUST_LOG` 进行级别过滤
43///(未设置时默认为 `info`)。输出到 stderr。
44///
45/// # Errors
46///
47/// 全局订阅者已被设置时返回错误
48///(例如之前已调用 `init_logging` 或 `init_logging_json`)。
49pub fn init_logging_json() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
50    tracing_subscriber::fmt()
51        .with_env_filter(
52            EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")),
53        )
54        .json()
55        .try_init()
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn init_logging_does_not_panic() {
64        // `try_init` may fail if a subscriber is already set (e.g. another
65        // test ran first). This must not panic.
66        let _ = init_logging();
67    }
68
69    #[test]
70    fn init_logging_json_does_not_panic() {
71        let _ = init_logging_json();
72    }
73}