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::{self, 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#[derive(Clone, Copy, Debug)]
13pub enum ServiceName {
14    Manager,
15    Runner,
16    CompilerServer,
17    ControlPlane,
18    KubernetesRunner,
19    Pipeline,
20}
21
22impl ServiceName {
23    pub fn as_str(self) -> &'static str {
24        match self {
25            ServiceName::Manager => "manager",
26            ServiceName::Runner => "runner",
27            ServiceName::CompilerServer => "compiler-server",
28            ServiceName::ControlPlane => "control-plane",
29            ServiceName::KubernetesRunner => "kubernetes-runner",
30            ServiceName::Pipeline => "pipeline",
31        }
32    }
33}
34
35impl From<ServiceName> for String {
36    fn from(value: ServiceName) -> Self {
37        value.as_str().to_string()
38    }
39}
40
41#[derive(Clone)]
42pub enum LogIdentity {
43    /// Control-plane component (manager | runner | compiler-server | control-plane).
44    Service { service_name: Option<ServiceName> },
45    /// Pipeline log source.
46    Pipeline {
47        pipeline_name: Option<String>,
48        pipeline_id: Option<String>,
49    },
50}
51
52/// Shared JSON formatter that injects pipeline/service name and structured fields.
53pub struct JsonPipelineFormat {
54    identity: LogIdentity,
55}
56
57impl JsonPipelineFormat {
58    pub fn new(identity: LogIdentity) -> Self {
59        Self { identity }
60    }
61}
62
63impl<S, N> FormatEvent<S, N> for JsonPipelineFormat
64where
65    S: Subscriber + for<'a> LookupSpan<'a>,
66    N: for<'a> FormatFields<'a> + 'static,
67{
68    fn format_event(
69        &self,
70        ctx: &tracing_subscriber::fmt::FmtContext<'_, S, N>,
71        mut writer: Writer<'_>,
72        event: &tracing::Event<'_>,
73    ) -> std::fmt::Result {
74        let mut visitor = SerdeVisitor::default();
75        event.record(&mut visitor);
76
77        // Defaults from the configured identity.
78        let mut pipeline_name = match &self.identity {
79            LogIdentity::Service { .. } => None,
80            LogIdentity::Pipeline {
81                pipeline_name,
82                pipeline_id: _,
83            } => pipeline_name.clone(),
84        };
85        let mut pipeline_id = match &self.identity {
86            LogIdentity::Service { .. } => None,
87            LogIdentity::Pipeline { pipeline_id, .. } => pipeline_id.clone(),
88        };
89        let mut feldera_service = match &self.identity {
90            LogIdentity::Service { service_name } => {
91                service_name.map(|service| service.as_str().to_string())
92            }
93            LogIdentity::Pipeline { .. } => Some(ServiceName::Pipeline.as_str().to_string()),
94        };
95
96        // Allow structured fields to override the defaults.
97        if let Some(value) = visitor.fields.remove("pipeline-name") {
98            pipeline_name = value_to_string(value);
99        } else if let Some(value) = visitor.fields.remove("pipeline") {
100            pipeline_name = value_to_string(value);
101        }
102        if let Some(value) = visitor.fields.remove("pipeline-id") {
103            pipeline_id = value_to_string(value);
104        } else if let Some(value) = visitor.fields.remove("pipeline_id") {
105            pipeline_id = value_to_string(value);
106        }
107        if let Some(value) = visitor.fields.remove("feldera-service") {
108            feldera_service = value_to_string(value);
109        }
110
111        let metadata = event.metadata();
112        // Default service tagging based on module path when logs come from shared binaries.
113        if metadata.target().starts_with("pipeline_manager::runner")
114            && feldera_service.as_deref() != Some("runner")
115        {
116            feldera_service = Some("runner".to_string());
117        } else if metadata.target().starts_with("pipeline_manager::compiler")
118            && feldera_service.as_deref() != Some("compiler-server")
119        {
120            feldera_service = Some("compiler-server".to_string());
121        } else if metadata
122            .target()
123            .starts_with("cluster_control_plane::kubernetes_runner")
124            && feldera_service.as_deref() != Some("kubernetes-runner")
125        {
126            feldera_service = Some("kubernetes-runner".to_string());
127        }
128        let mut obj = Map::new();
129        obj.insert("timestamp".to_string(), Value::String(now_timestamp()));
130        obj.insert(
131            "level".to_string(),
132            Value::String(metadata.level().as_str().to_string()),
133        );
134        obj.insert(
135            "target".to_string(),
136            Value::String(metadata.target().to_string()),
137        );
138        if let Some(service_name) = feldera_service {
139            obj.insert("feldera-service".to_string(), Value::String(service_name));
140        }
141        if let Some(pipeline_name) = pipeline_name {
142            obj.insert("pipeline-name".to_string(), Value::String(pipeline_name));
143        }
144        if let Some(pipeline_id) = pipeline_id {
145            obj.insert("pipeline-id".to_string(), Value::String(pipeline_id));
146        }
147        obj.insert("fields".to_string(), Value::Object(visitor.fields));
148
149        if let Some(span) = ctx.lookup_current() {
150            obj.insert("span".to_string(), Value::String(span.name().to_string()));
151        }
152
153        let json = Value::Object(obj);
154        writeln!(writer, "{}", json)
155    }
156}
157
158#[derive(Default)]
159pub struct SerdeVisitor {
160    pub fields: Map<String, Value>,
161}
162
163impl tracing::field::Visit for SerdeVisitor {
164    fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
165        self.fields.insert(
166            field.name().to_string(),
167            Value::String(format!("{value:?}")),
168        );
169    }
170
171    fn record_f64(&mut self, field: &tracing::field::Field, value: f64) {
172        let as_number = serde_json::Number::from_f64(value);
173        let val = as_number
174            .map(Value::Number)
175            .unwrap_or_else(|| Value::String(value.to_string()));
176        self.fields.insert(field.name().to_string(), val);
177    }
178
179    fn record_i128(&mut self, field: &tracing::field::Field, value: i128) {
180        let val = i64::try_from(value)
181            .map(|v| Value::Number(v.into()))
182            .unwrap_or_else(|_| Value::String(value.to_string()));
183        self.fields.insert(field.name().to_string(), val);
184    }
185
186    fn record_u128(&mut self, field: &tracing::field::Field, value: u128) {
187        let val = u64::try_from(value)
188            .map(|v| Value::Number(v.into()))
189            .unwrap_or_else(|_| Value::String(value.to_string()));
190        self.fields.insert(field.name().to_string(), val);
191    }
192
193    fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
194        self.fields
195            .insert(field.name().to_string(), Value::String(value.to_string()));
196    }
197
198    fn record_i64(&mut self, field: &tracing::field::Field, value: i64) {
199        self.fields
200            .insert(field.name().to_string(), Value::Number(value.into()));
201    }
202
203    fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {
204        self.fields
205            .insert(field.name().to_string(), Value::Number(value.into()));
206    }
207
208    fn record_bool(&mut self, field: &tracing::field::Field, value: bool) {
209        self.fields
210            .insert(field.name().to_string(), Value::Bool(value));
211    }
212}
213
214fn now_timestamp() -> String {
215    Utc::now().format("%Y-%m-%dT%H:%M:%S%.6fZ").to_string()
216}
217
218/// True when structured JSON logging is requested via `FELDERA_LOG_JSON`.
219pub fn use_json_log_format() -> bool {
220    matches!(
221        std::env::var("FELDERA_LOG_JSON")
222            .unwrap_or_default()
223            .to_ascii_lowercase()
224            .as_str(),
225        "1" | "true" | "yes" | "on"
226    )
227}
228
229/// Remove surrounding `[]` often used in pretty log prefixes.
230pub fn sanitize_pipeline_name(name: impl AsRef<str>) -> String {
231    name.as_ref()
232        .trim_matches(|c| c == '[' || c == ']')
233        .to_string()
234}
235
236/// Initialize logging with either the JSON or text pipeline format.
237pub fn init_pipeline_logging(
238    pipeline_name: ColoredString,
239    env_filter: EnvFilter,
240) -> Result<(), tracing_subscriber::util::TryInitError> {
241    init_pipeline_logging_with_id(pipeline_name, None, env_filter)
242}
243
244/// Initialize logging with either the JSON or text pipeline format, optionally attaching a pipeline id.
245pub fn init_pipeline_logging_with_id(
246    pipeline_name: ColoredString,
247    pipeline_id: Option<String>,
248    env_filter: EnvFilter,
249) -> Result<(), tracing_subscriber::util::TryInitError> {
250    init_logging(
251        pipeline_name,
252        LogIdentity::Pipeline {
253            pipeline_name: None,
254            pipeline_id,
255        },
256        env_filter,
257    )
258}
259
260/// Initialize logging for a control-plane service (manager | runner | compiler-server | control-plane).
261pub fn init_service_logging(
262    service_name: ColoredString,
263    feldera_service: ServiceName,
264    env_filter: EnvFilter,
265) -> Result<(), tracing_subscriber::util::TryInitError> {
266    init_logging(
267        service_name,
268        LogIdentity::Service {
269            service_name: Some(feldera_service),
270        },
271        env_filter,
272    )
273}
274
275fn init_logging(
276    prefix: ColoredString,
277    identity: LogIdentity,
278    env_filter: EnvFilter,
279) -> Result<(), tracing_subscriber::util::TryInitError> {
280    let identity = match identity {
281        LogIdentity::Service { service_name } => LogIdentity::Service {
282            service_name: service_name.or(Some(ServiceName::ControlPlane)),
283        },
284        LogIdentity::Pipeline {
285            pipeline_name,
286            pipeline_id,
287        } => LogIdentity::Pipeline {
288            pipeline_name: Some(
289                pipeline_name
290                    .unwrap_or_else(|| sanitize_pipeline_name(prefix.clone().clear().to_string())),
291            ),
292            pipeline_id,
293        },
294    };
295
296    if use_json_log_format() {
297        tracing_subscriber::registry()
298            .with(
299                tracing_subscriber::fmt::layer()
300                    .event_format(JsonPipelineFormat::new(identity))
301                    .with_ansi(false),
302            )
303            .with(env_filter)
304            .with(sentry::integrations::tracing::layer())
305            .try_init()
306    } else {
307        tracing_subscriber::registry()
308            .with(
309                tracing_subscriber::fmt::layer()
310                    .event_format(FormatWithPrefix::new(prefix))
311                    .fmt_fields(plain_text_fields()),
312            )
313            .with(env_filter)
314            .with(sentry::integrations::tracing::layer())
315            .try_init()
316    }
317}
318
319/// Text formatter that prepends the pipeline name to each event.
320pub struct FormatWithPrefix {
321    pipeline_name: ColoredString,
322    inner: Format,
323}
324
325impl FormatWithPrefix {
326    pub fn new(pipeline_name: ColoredString) -> Self {
327        Self {
328            pipeline_name,
329            inner: Format::default(),
330        }
331    }
332}
333
334impl<S, N> FormatEvent<S, N> for FormatWithPrefix
335where
336    S: Subscriber + for<'a> LookupSpan<'a>,
337    N: for<'a> FormatFields<'a> + 'static,
338{
339    fn format_event(
340        &self,
341        ctx: &tracing_subscriber::fmt::FmtContext<'_, S, N>,
342        mut writer: Writer<'_>,
343        event: &tracing::Event<'_>,
344    ) -> std::fmt::Result {
345        write!(writer, "{} ", self.pipeline_name)?;
346        self.inner.format_event(ctx, writer, event)
347    }
348}
349
350fn value_to_string(value: Value) -> Option<String> {
351    match value {
352        Value::String(s) => Some(s),
353        Value::Number(n) => Some(n.to_string()),
354        Value::Bool(b) => Some(b.to_string()),
355        Value::Null => None,
356        other => Some(other.to_string()),
357    }
358}
359
360/// In plain text, render the message plus selected structured fields.
361fn plain_text_fields() -> impl for<'writer> tracing_subscriber::fmt::FormatFields<'writer> + Clone {
362    format::debug_fn(|writer, field, value| {
363        match field.name() {
364            "message" => {
365                write!(writer, " {value:?}")?;
366            }
367            "pipeline" | "pipeline_name" | "pipeline-name" => {
368                write!(writer, " pipeline-name={value:?}")?;
369            }
370            "pipeline_id" | "pipeline-id" => {
371                write!(writer, " pipeline-id={value:?}")?;
372            }
373            "tenant" => {
374                write!(writer, " tenant={value:?}")?;
375            }
376            _ => {}
377        }
378        Ok(())
379    })
380}