Skip to main content

flare_core_infra/telemetry/
mod.rs

1//! 进程级日志与 trace 订阅器初始化(`tracing-subscriber` + `tracing-log` + 可选 OTLP),与具体业务配置解耦。
2//!
3//! IM 等上层可把 TOML 中的日志字段映射为 [LoggingSubscriberOptions] 后调用 [init_fmt_subscriber];
4//! 需要端到端 trace 时调用 [init_tracing_subscriber] 并传入 [OtlpTracingOptions]。
5
6use std::error::Error;
7
8use tracing_subscriber::{EnvFilter, fmt, layer::SubscriberExt, util::SubscriberInitExt};
9
10type TelemetryInitResult<T> = Result<T, Box<dyn Error + Send + Sync>>;
11
12/// 与典型 YAML/TOML 日志段对齐的 fmt 层选项(不依赖任何应用配置类型)
13#[derive(Debug, Clone)]
14pub struct LoggingSubscriberOptions {
15    pub level: String,
16    pub with_target: bool,
17    pub with_thread_ids: bool,
18    pub with_file: bool,
19    pub with_line_number: bool,
20    pub with_ansi: Option<bool>,
21}
22
23/// OTLP trace exporter 配置。
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct OtlpTracingOptions {
26    pub service_name: String,
27    pub endpoint: String,
28}
29
30impl OtlpTracingOptions {
31    pub fn new(service_name: impl Into<String>, endpoint: impl Into<String>) -> Self {
32        Self {
33            service_name: service_name.into(),
34            endpoint: endpoint.into(),
35        }
36    }
37
38    fn enabled(&self) -> bool {
39        !self.service_name.trim().is_empty() && !self.endpoint.trim().is_empty()
40    }
41}
42
43impl Default for LoggingSubscriberOptions {
44    fn default() -> Self {
45        Self {
46            level: "debug".to_string(),
47            with_target: false,
48            with_thread_ids: true,
49            with_file: true,
50            with_line_number: true,
51            with_ansi: None,
52        }
53    }
54}
55
56/// 无 `RUST_LOG` 时:业务用 `level`,第三方库降噪。
57///
58/// 与 `flare-im-core/scripts/start_server.sh` 中默认 `RUST_LOG` 保持同类项一致,避免本地 `logs/` 被
59/// `sqlx` / `tokio` / NATS / gRPC 栈在 `trace` 下刷到数 GB。
60fn default_env_filter(app_level: &str) -> EnvFilter {
61    let s = format!(
62        "{},hyper=warn,reqwest=warn,h2=warn,rdkafka=warn,tower=warn,tokio=warn,sqlx=warn,tantivy=warn,async_nats=warn,tonic=warn,redis=warn",
63        app_level
64    );
65    EnvFilter::try_new(&s).unwrap_or_else(|_| EnvFilter::new(app_level))
66}
67
68fn stdout_is_terminal() -> bool {
69    use std::io::IsTerminal;
70    std::io::stdout().is_terminal()
71}
72
73/// 安装全局 fmt subscriber:`log` crate 事件经 `tracing-log` 汇入同一流。
74///
75/// * `options` — `None` 时使用 [LoggingSubscriberOptions::default]。
76/// * 已存在全局 subscriber 时静默跳过(`try_init`),避免测试/重复启动 panic。
77pub fn init_fmt_subscriber(options: Option<&LoggingSubscriberOptions>) {
78    let _ = init_tracing_subscriber(options, None);
79}
80
81/// 安装全局 tracing subscriber,可选启用 OTLP trace exporter。
82///
83/// 已存在全局 subscriber 时静默跳过,保持重复初始化安全;OTLP exporter 构建失败会返回错误。
84pub fn init_tracing_subscriber(
85    options: Option<&LoggingSubscriberOptions>,
86    otlp: Option<&OtlpTracingOptions>,
87) -> TelemetryInitResult<()> {
88    let _ = tracing_log::LogTracer::init();
89
90    let opts = options.cloned().unwrap_or_default();
91    let env_filter = match EnvFilter::try_from_default_env() {
92        Ok(filter) => filter,
93        Err(_) => default_env_filter(opts.level.as_str()),
94    };
95
96    let use_ansi = opts.with_ansi.unwrap_or_else(stdout_is_terminal);
97    if let Some(otlp) = otlp.filter(|options| options.enabled()) {
98        init_subscriber_with_otlp(&opts, env_filter, use_ansi, otlp)?;
99    } else {
100        let fmt_layer = fmt::layer()
101            .with_ansi(use_ansi)
102            .with_target(opts.with_target)
103            .with_thread_ids(opts.with_thread_ids)
104            .with_file(opts.with_file)
105            .with_line_number(opts.with_line_number);
106        let _ = tracing_subscriber::registry()
107            .with(env_filter)
108            .with(fmt_layer)
109            .try_init();
110    }
111
112    Ok(())
113}
114
115#[cfg(feature = "otel")]
116fn init_subscriber_with_otlp(
117    opts: &LoggingSubscriberOptions,
118    env_filter: EnvFilter,
119    use_ansi: bool,
120    otlp: &OtlpTracingOptions,
121) -> TelemetryInitResult<()> {
122    use opentelemetry::trace::TracerProvider as _;
123    use opentelemetry_otlp::WithExportConfig as _;
124    use opentelemetry_sdk::{Resource, trace::SdkTracerProvider};
125
126    let exporter = opentelemetry_otlp::SpanExporter::builder()
127        .with_tonic()
128        .with_endpoint(otlp.endpoint.trim().to_string())
129        .build()?;
130    let provider = SdkTracerProvider::builder()
131        .with_resource(
132            Resource::builder()
133                .with_service_name(otlp.service_name.trim().to_string())
134                .build(),
135        )
136        .with_batch_exporter(exporter)
137        .build();
138    let tracer = provider.tracer(otlp.service_name.trim().to_string());
139    opentelemetry::global::set_tracer_provider(provider);
140
141    let fmt_layer = fmt::layer()
142        .with_ansi(use_ansi)
143        .with_target(opts.with_target)
144        .with_thread_ids(opts.with_thread_ids)
145        .with_file(opts.with_file)
146        .with_line_number(opts.with_line_number);
147    let otel_layer = tracing_opentelemetry::layer().with_tracer(tracer);
148    let _ = tracing_subscriber::registry()
149        .with(env_filter)
150        .with(fmt_layer)
151        .with(otel_layer)
152        .try_init();
153
154    Ok(())
155}
156
157#[cfg(not(feature = "otel"))]
158fn init_subscriber_with_otlp(
159    opts: &LoggingSubscriberOptions,
160    env_filter: EnvFilter,
161    use_ansi: bool,
162    otlp: &OtlpTracingOptions,
163) -> TelemetryInitResult<()> {
164    let fmt_layer = fmt::layer()
165        .with_ansi(use_ansi)
166        .with_target(opts.with_target)
167        .with_thread_ids(opts.with_thread_ids)
168        .with_file(opts.with_file)
169        .with_line_number(opts.with_line_number);
170    let _ = tracing_subscriber::registry()
171        .with(env_filter)
172        .with(fmt_layer)
173        .try_init();
174    tracing::warn!(
175        service_name = %otlp.service_name,
176        endpoint = %otlp.endpoint,
177        "OTLP tracing requested but flare-core-infra was built without the `otel` feature"
178    );
179    Ok(())
180}