refactor: add shared logging crate
This commit is contained in:
22
server-rs/crates/shared-logging/src/lib.rs
Normal file
22
server-rs/crates/shared-logging/src/lib.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
use std::io;
|
||||
|
||||
use tracing_subscriber::{fmt, EnvFilter};
|
||||
|
||||
// 统一解析工作区日志过滤器,优先环境变量,其次回落到调用方传入的默认值。
|
||||
pub fn resolve_env_filter(default_filter: &str) -> EnvFilter {
|
||||
EnvFilter::try_from_default_env()
|
||||
.or_else(|_| EnvFilter::try_new(default_filter))
|
||||
.unwrap_or_else(|_| EnvFilter::new("info"))
|
||||
}
|
||||
|
||||
// 统一初始化 tracing subscriber,避免各入口重复散落相同配置。
|
||||
pub fn init_tracing(default_filter: &str) -> Result<(), io::Error> {
|
||||
let env_filter = resolve_env_filter(default_filter);
|
||||
|
||||
fmt()
|
||||
.with_env_filter(env_filter)
|
||||
.with_target(true)
|
||||
.compact()
|
||||
.try_init()
|
||||
.map_err(|error| io::Error::other(format!("初始化 tracing subscriber 失败:{error}")))
|
||||
}
|
||||
Reference in New Issue
Block a user