Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

tracing otel link (#1387)

Will Hutchinson8072e5eb896c
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 5c3e54c1c1..ec765a3771 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -5026,6 +5026,7 @@ dependencies = [
"opentelemetry",
"opentelemetry-otlp",
"opentelemetry_sdk",
+ "serde_json",
"tracing",
"tracing-opentelemetry",
"tracing-panic",
diff --git a/rust/cloud-storage/macro_entrypoint/Cargo.toml b/rust/cloud-storage/macro_entrypoint/Cargo.toml
index 2de2ef2433..c36647c057 100644
--- a/rust/cloud-storage/macro_entrypoint/Cargo.toml
+++ b/rust/cloud-storage/macro_entrypoint/Cargo.toml
@@ -10,6 +10,7 @@ macro_env = { path = "../macro_env" }
opentelemetry = { workspace = true }
opentelemetry_sdk = { workspace = true }
opentelemetry-otlp = { workspace = true }
+serde_json = { workspace = true }
tracing = { workspace = true }
tracing-opentelemetry = { workspace = true }
tracing-panic = "0.1"
diff --git a/rust/cloud-storage/macro_entrypoint/src/datadog_fmt.rs b/rust/cloud-storage/macro_entrypoint/src/datadog_fmt.rs
new file mode 100644
index 0000000000..0e0cc4a9fe
--- /dev/null
+++ b/rust/cloud-storage/macro_entrypoint/src/datadog_fmt.rs
@@ -0,0 +1,85 @@
+//! Datadog trace-log correlation for JSON logs.
+//!
+//! Wraps a [`FormatEvent`] to inject `dd.trace_id` and `dd.span_id` into each
+//! JSON log line so that Datadog APM can correlate logs with distributed traces.
+
+use opentelemetry::trace::TraceContextExt as _;
+use tracing::Subscriber;
+use tracing_opentelemetry::OpenTelemetrySpanExt as _;
+use tracing_subscriber::{
+ fmt::{FmtContext, FormatEvent, FormatFields, format},
+ registry::LookupSpan,
+};
+
+/// Wraps an inner [`FormatEvent`] formatter to inject `dd.trace_id` and
+/// `dd.span_id` into each JSON log line.
+///
+/// Datadog expects trace IDs as the lower 64 bits of the 128-bit OpenTelemetry
+/// trace ID, represented as a decimal string.
+pub(crate) struct DatadogFormat<F> {
+ pub(crate) inner: F,
+}
+
+impl<S, N, F> FormatEvent<S, N> for DatadogFormat<F>
+where
+ S: Subscriber + for<'a> LookupSpan<'a>,
+ N: for<'a> FormatFields<'a> + 'static,
+ F: FormatEvent<S, N>,
+{
+ fn format_event(
+ &self,
+ ctx: &FmtContext<'_, S, N>,
+ mut writer: format::Writer<'_>,
+ event: &tracing::Event<'_>,
+ ) -> std::fmt::Result {
+ // Delegate to the inner JSON formatter, writing to a buffer.
+ let mut buf = String::new();
+ self.inner
+ .format_event(ctx, format::Writer::new(&mut buf), event)?;
+
+ // Parse the JSON, inject DD trace fields, re-serialize.
+ let trimmed = buf.trim_end();
+ match serde_json::from_str::<serde_json::Value>(trimmed) {
+ Ok(mut json) => {
+ if let Some(obj) = json.as_object_mut() {
+ inject_dd_trace_context(obj);
+ }
+ let out = serde_json::to_string(&json).map_err(|_| std::fmt::Error)?;
+ writeln!(writer, "{out}")
+ }
+ // If parsing fails, pass the original output through unchanged.
+ Err(_) => writer.write_str(&buf),
+ }
+ }
+}
+
+/// Read the OpenTelemetry span context from the current [`tracing::Span`] and
+/// insert `dd.trace_id` / `dd.span_id` as decimal strings.
+fn inject_dd_trace_context(obj: &mut serde_json::Map<String, serde_json::Value>) {
+ let span = tracing::Span::current();
+ let cx = span.context();
+ let otel_span = cx.span();
+ let sc = otel_span.span_context();
+
+ if !sc.is_valid() {
+ return;
+ }
+
+ // Datadog trace ID = lower 64 bits of the 128-bit OTel trace ID, as decimal.
+ let trace_bytes = sc.trace_id().to_bytes();
+ let dd_trace_id = u64::from_be_bytes(
+ trace_bytes[8..16]
+ .try_into()
+ .expect("slice is always 8 bytes"),
+ );
+ let dd_span_id = u64::from_be_bytes(sc.span_id().to_bytes());
+
+ obj.insert(
+ "dd.trace_id".into(),
+ serde_json::Value::String(dd_trace_id.to_string()),
+ );
+ obj.insert(
+ "dd.span_id".into(),
+ serde_json::Value::String(dd_span_id.to_string()),
+ );
+}
diff --git a/rust/cloud-storage/macro_entrypoint/src/lib.rs b/rust/cloud-storage/macro_entrypoint/src/lib.rs
index 5bd7128151..0c7d40591b 100644
--- a/rust/cloud-storage/macro_entrypoint/src/lib.rs
+++ b/rust/cloud-storage/macro_entrypoint/src/lib.rs
@@ -2,6 +2,8 @@
//! This crate provides a standardized initialization process that should be used across entrypoint crates.
//! This is used to provide consistent behaviour with e.g. tracing configurations
+mod datadog_fmt;
+
use macro_env::Environment;
use opentelemetry::trace::TracerProvider as _;
use opentelemetry_otlp::WithExportConfig;
@@ -96,15 +98,21 @@ impl MacroEntrypoint {
let tracer = tracer_provider.tracer(service_name);
let otel_layer = tracing_opentelemetry::layer().with_tracer(tracer);
- let fmt_layer = tracing_subscriber::fmt::layer()
- .with_ansi(false)
- .with_file(true)
- .with_line_number(true)
+ // Build the JSON event format, then wrap it with DatadogFormat
+ // to inject dd.trace_id / dd.span_id for trace-log correlation.
+ let json_format = tracing_subscriber::fmt::format::Format::default()
.json()
.with_current_span(true)
.with_span_list(false)
.flatten_event(true);
+ let fmt_layer = tracing_subscriber::fmt::layer()
+ .with_ansi(false)
+ .with_file(true)
+ .with_line_number(true)
+ .fmt_fields(tracing_subscriber::fmt::format::JsonFields::new())
+ .event_format(datadog_fmt::DatadogFormat { inner: json_format });
+
Registry::default()
.with(EnvFilter::from_default_env())
.with(fmt_layer)