feldera_observability/
json_logging.rs

1use chrono::Utc;
2use colored::{ColoredString, Colorize};
3use serde_json::{Map, Value};
4use tracing::Subscriber;
5use tracing_subscriber::fmt::format::{Format, Writer};
6use tracing_subscriber::fmt::{FormatEvent, FormatFields};
7use tracing_subscriber::layer::SubscriberExt;
8use tracing_subscriber::registry::LookupSpan;
9use tracing_subscriber::util::SubscriberInitExt;
10use tracing_subscriber::EnvFilter;
11
12/// Shared JSON formatter that injects pipeline/service name and structured fields.
13pub struct JsonPipelineFormat {
14    pipeline: String,
15    pipeline_id: Option<String>,
16}
17
18impl JsonPipelineFormat {
19    pub fn new(pipeline: String, pipeline_id: Option<String>) -> Self {
20        Self {
21            pipeline,
22            pipeline_id,
23        }
24    }
25}
26
27impl<S, N> FormatEvent<S, N> for JsonPipelineFormat
28where
29    S: Subscriber + for<'a> LookupSpan<'a>,
30    N: for<'a> FormatFields<'a> + 'static,
31{
32    fn format_event(
33        &self,
34        ctx: &tracing_subscriber::fmt::FmtContext<'_, S, N>,
35        mut writer: Writer<'_>,
36        event: &tracing::Event<'_>,
37    ) -> std::fmt::Result {
38        let mut visitor = SerdeVisitor::default();
39        event.record(&mut visitor);
40
41        let metadata = event.metadata();
42        let mut obj = Map::new();
43        obj.insert("timestamp".to_string(), Value::String(now_timestamp()));
44        obj.insert(
45            "level".to_string(),
46            Value::String(metadata.level().as_str().to_string()),
47        );
48        obj.insert(
49            "target".to_string(),
50            Value::String(metadata.target().to_string()),
51        );
52        obj.insert("pipeline".to_string(), Value::String(self.pipeline.clone()));
53        obj.insert(
54            "pipeline-id".to_string(),
55            self.pipeline_id
56                .as_ref()
57                .map(|v| Value::String(v.clone()))
58                .unwrap_or(Value::Null),
59        );
60        obj.insert("fields".to_string(), Value::Object(visitor.fields));
61
62        if let Some(span) = ctx.lookup_current() {
63            obj.insert("span".to_string(), Value::String(span.name().to_string()));
64        }
65
66        let json = Value::Object(obj);
67        writeln!(writer, "{}", json)
68    }
69}
70
71#[derive(Default)]
72pub struct SerdeVisitor {
73    pub fields: Map<String, Value>,
74}
75
76impl tracing::field::Visit for SerdeVisitor {
77    fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
78        self.fields.insert(
79            field.name().to_string(),
80            Value::String(format!("{value:?}")),
81        );
82    }
83
84    fn record_f64(&mut self, field: &tracing::field::Field, value: f64) {
85        let as_number = serde_json::Number::from_f64(value);
86        let val = as_number
87            .map(Value::Number)
88            .unwrap_or_else(|| Value::String(value.to_string()));
89        self.fields.insert(field.name().to_string(), val);
90    }
91
92    fn record_i128(&mut self, field: &tracing::field::Field, value: i128) {
93        let val = i64::try_from(value)
94            .map(|v| Value::Number(v.into()))
95            .unwrap_or_else(|_| Value::String(value.to_string()));
96        self.fields.insert(field.name().to_string(), val);
97    }
98
99    fn record_u128(&mut self, field: &tracing::field::Field, value: u128) {
100        let val = u64::try_from(value)
101            .map(|v| Value::Number(v.into()))
102            .unwrap_or_else(|_| Value::String(value.to_string()));
103        self.fields.insert(field.name().to_string(), val);
104    }
105
106    fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
107        self.fields
108            .insert(field.name().to_string(), Value::String(value.to_string()));
109    }
110
111    fn record_i64(&mut self, field: &tracing::field::Field, value: i64) {
112        self.fields
113            .insert(field.name().to_string(), Value::Number(value.into()));
114    }
115
116    fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {
117        self.fields
118            .insert(field.name().to_string(), Value::Number(value.into()));
119    }
120
121    fn record_bool(&mut self, field: &tracing::field::Field, value: bool) {
122        self.fields
123            .insert(field.name().to_string(), Value::Bool(value));
124    }
125}
126
127fn now_timestamp() -> String {
128    Utc::now().format("%Y-%m-%dT%H:%M:%S%.6fZ").to_string()
129}
130
131/// True when structured JSON logging is requested via `FELDERA_LOG_JSON`.
132pub fn use_json_log_format() -> bool {
133    matches!(
134        std::env::var("FELDERA_LOG_JSON")
135            .unwrap_or_default()
136            .to_ascii_lowercase()
137            .as_str(),
138        "1" | "true" | "yes" | "on"
139    )
140}
141
142/// Remove surrounding `[]` often used in pretty log prefixes.
143pub fn sanitize_pipeline_name(name: impl AsRef<str>) -> String {
144    name.as_ref()
145        .trim_matches(|c| c == '[' || c == ']')
146        .to_string()
147}
148
149/// Initialize logging with either the JSON or text pipeline format.
150pub fn init_pipeline_logging(
151    pipeline_name: ColoredString,
152    env_filter: EnvFilter,
153) -> Result<(), tracing_subscriber::util::TryInitError> {
154    init_pipeline_logging_with_id(pipeline_name, None, env_filter)
155}
156
157/// Initialize logging with either the JSON or text pipeline format, optionally attaching a pipeline id.
158pub fn init_pipeline_logging_with_id(
159    pipeline_name: ColoredString,
160    pipeline_id: Option<String>,
161    env_filter: EnvFilter,
162) -> Result<(), tracing_subscriber::util::TryInitError> {
163    if use_json_log_format() {
164        let pipeline_name_json = sanitize_pipeline_name(pipeline_name.clone().clear().to_string());
165        tracing_subscriber::registry()
166            .with(
167                tracing_subscriber::fmt::layer()
168                    .event_format(JsonPipelineFormat::new(pipeline_name_json, pipeline_id))
169                    .with_ansi(false),
170            )
171            .with(env_filter)
172            .with(sentry::integrations::tracing::layer())
173            .try_init()
174    } else {
175        tracing_subscriber::registry()
176            .with(
177                tracing_subscriber::fmt::layer().event_format(FormatWithPrefix::new(pipeline_name)),
178            )
179            .with(env_filter)
180            .with(sentry::integrations::tracing::layer())
181            .try_init()
182    }
183}
184
185/// Text formatter that prepends the pipeline name to each event.
186pub struct FormatWithPrefix {
187    pipeline_name: ColoredString,
188    inner: Format,
189}
190
191impl FormatWithPrefix {
192    pub fn new(pipeline_name: ColoredString) -> Self {
193        Self {
194            pipeline_name,
195            inner: Format::default(),
196        }
197    }
198}
199
200impl<S, N> FormatEvent<S, N> for FormatWithPrefix
201where
202    S: Subscriber + for<'a> LookupSpan<'a>,
203    N: for<'a> FormatFields<'a> + 'static,
204{
205    fn format_event(
206        &self,
207        ctx: &tracing_subscriber::fmt::FmtContext<'_, S, N>,
208        mut writer: Writer<'_>,
209        event: &tracing::Event<'_>,
210    ) -> std::fmt::Result {
211        write!(writer, "{} ", self.pipeline_name)?;
212        self.inner.format_event(ctx, writer, event)
213    }
214}