secra_logger/
field_normalization.rs

1//! 字段规范化层
2//!
3//! 提供日志字段规范化功能,遵循 OpenTelemetry 语义约定。
4
5use std::collections::HashMap;
6use tracing_subscriber::layer::Layer;
7use tracing::Event;
8
9/// 字段规范化 Layer
10///
11/// 初期阶段提供基础实现,后续可以扩展
12#[allow(dead_code)]
13pub struct FieldNormalizationLayer {
14    mappings: HashMap<String, String>,
15    enabled: bool,
16}
17
18impl FieldNormalizationLayer {
19    /// 创建新的字段规范化层
20    #[allow(dead_code)]
21    pub fn new(mappings: HashMap<String, String>, enabled: bool) -> Self {
22        Self {
23            mappings,
24            enabled,
25        }
26    }
27}
28
29impl<S> Layer<S> for FieldNormalizationLayer
30where
31    S: tracing::Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
32{
33    fn on_event(&self, _event: &Event<'_>, _ctx: tracing_subscriber::layer::Context<'_, S>) {
34        if !self.enabled {
35            return;
36        }
37        
38        // 字段规范化逻辑
39        // 注意:tracing-subscriber 的 JSON formatter 会自动处理字段,
40        // 这里主要提供扩展点,实际规范化可以在格式化阶段进行
41        // 初期阶段提供基础实现,后续可以扩展
42    }
43}
44
45/// 规范化字段名(驼峰转点分隔)
46///
47/// 遵循 OpenTelemetry 语义约定:
48/// - HTTP 请求:`http.method`, `http.path`, `http.status_code`
49/// - 数据库:`db.system`, `db.name`, `db.operation`
50/// - 服务:`service.name`, `service.version`
51/// - 请求追踪:`trace_id`, `span_id`, `request_id`
52/// - 用户:`user.id`, `user.email`
53#[allow(dead_code)]
54pub fn normalize_field_name(name: &str) -> String {
55    // 如果字段名已经符合规范(包含点),直接返回
56    if name.contains('.') {
57        return name.to_string();
58    }
59    
60    // 简单的驼峰转点分隔(基础实现)
61    // 例如:httpMethod -> http.method
62    let mut result = String::new();
63    let mut chars = name.chars().peekable();
64    
65    while let Some(ch) = chars.next() {
66        if ch.is_uppercase() && !result.is_empty() {
67            result.push('.');
68            result.push(ch.to_lowercase().next().unwrap());
69        } else {
70            result.push(ch.to_lowercase().next().unwrap());
71        }
72    }
73    
74    result
75}