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