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