Skip to main content

feldera_observability/
json_logging.rs

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