Skip to content

feat: otel feature, writing the OTel trace ID #2662

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions tracing-subscriber/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ valuable = ["tracing-core/valuable", "valuable_crate", "valuable-serde", "tracin
# Enables support for local time when using the `time` crate timestamp
# formatters.
local-time = ["time/local-offset"]
otel = ["opentelemetry"]

[dependencies]
tracing-core = { path = "../tracing-core", version = "0.1.30", default-features = false }
Expand Down Expand Up @@ -64,6 +65,9 @@ parking_lot = { version = "0.12.1", optional = true }
sharded-slab = { version = "0.1.4", optional = true }
thread_local = { version = "1.1.4", optional = true }

# otel
opentelemetry = { version = "0.19", optional = true, default-features = false }

[target.'cfg(tracing_unstable)'.dependencies]
valuable_crate = { package = "valuable", version = "0.1.0", optional = true, default-features = false }
valuable-serde = { version = "0.1.0", optional = true, default-features = false }
Expand Down
14 changes: 12 additions & 2 deletions tracing-subscriber/src/fmt/fmt_layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,10 +311,10 @@ impl<S, N, E, W> Layer<S, N, E, W> {
/// By default, `fmt::Layer` will write any `FormatEvent`-internal errors to
/// the writer. These errors are unlikely and will only occur if there is a
/// bug in the `FormatEvent` implementation or its dependencies.
///
///
/// If writing to the writer fails, the error message is printed to stderr
/// as a fallback.
///
///
/// [`FormatEvent`]: crate::fmt::FormatEvent
pub fn log_internal_errors(self, log_internal_errors: bool) -> Self {
Self {
Expand Down Expand Up @@ -623,6 +623,16 @@ impl<S, T, W> Layer<S, format::JsonFields, format::Format<format::Json, T>, W> {
..self
}
}

/// Set the function to optionally make an OTel `TraceId`.
#[cfg(feature = "otel")]
pub fn with_make_trace_id(self, make_trace_id: Box<dyn format::MakeTraceId>) -> Self {
Layer {
fmt_event: self.fmt_event.with_make_trace_id(make_trace_id),
..self
}
}

}

impl<S, N, E, W> Layer<S, N, E, W> {
Expand Down
7 changes: 7 additions & 0 deletions tracing-subscriber/src/fmt/format/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,13 @@ where
.serialize_entry("threadId", &format!("{:?}", std::thread::current().id()))?;
}

#[cfg(feature = "otel")]
if let Some((make_trace_id, current_span)) = self.make_trace_id.as_ref().zip(current_span) {
if let Some(trace_id) = make_trace_id(current_span.extensions()) {
serializer.serialize_entry("trace_id", &trace_id.to_string())?;
}
}

serializer.end()
};

Expand Down
63 changes: 63 additions & 0 deletions tracing-subscriber/src/fmt/format/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ mod pretty;
#[cfg_attr(docsrs, doc(cfg(feature = "ansi")))]
pub use pretty::*;

#[cfg(feature = "otel")]
use crate::registry::Extensions;
#[cfg(feature = "otel")]
use opentelemetry::trace::TraceId;

/// A type that can format a tracing [`Event`] to a [`Writer`].
///
/// `FormatEvent` is primarily used in the context of [`fmt::Subscriber`] or
Expand Down Expand Up @@ -407,6 +412,43 @@ pub struct Format<F = Full, T = SystemTime> {
pub(crate) display_thread_name: bool,
pub(crate) display_filename: bool,
pub(crate) display_line_number: bool,
#[cfg(feature = "otel")]
pub(crate) make_trace_id: Option<Box<dyn MakeTraceId>>
}

/// Optionally make an OTel `TraceId`.
#[cfg(feature = "otel")]
pub trait MakeTraceId: Fn(Extensions<'_>) -> Option<TraceId> + Send + Sync {
/// Clone self into a boxed [MakeTraceId].
fn clone_box<'a>(&self) -> Box<dyn 'a + MakeTraceId>
where
Self: 'a;
}

#[cfg(feature = "otel")]
impl Debug for Box<dyn MakeTraceId> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "MakeTraceId")
}
}

#[cfg(feature = "otel")]
impl<F> MakeTraceId for F
where
F: Fn(Extensions<'_>) -> Option<TraceId> + Clone + Send + Sync {
fn clone_box<'a>(&self) -> Box<dyn 'a + MakeTraceId>
where
Self: 'a,
{
Box::new(self.clone())
}
}

#[cfg(feature = "otel")]
impl<'a> Clone for Box<dyn 'a + MakeTraceId> {
fn clone(&self) -> Self {
self.clone_box()
}
}

// === impl Writer ===
Expand Down Expand Up @@ -585,6 +627,8 @@ impl Default for Format<Full, SystemTime> {
display_thread_name: false,
display_filename: false,
display_line_number: false,
#[cfg(feature = "otel")]
make_trace_id: None,
}
}
}
Expand All @@ -605,6 +649,8 @@ impl<F, T> Format<F, T> {
display_thread_name: self.display_thread_name,
display_filename: self.display_filename,
display_line_number: self.display_line_number,
#[cfg(feature = "otel")]
make_trace_id: None,
}
}

Expand Down Expand Up @@ -644,6 +690,8 @@ impl<F, T> Format<F, T> {
display_thread_name: self.display_thread_name,
display_filename: true,
display_line_number: true,
#[cfg(feature = "otel")]
make_trace_id: None,
}
}

Expand Down Expand Up @@ -675,6 +723,8 @@ impl<F, T> Format<F, T> {
display_thread_name: self.display_thread_name,
display_filename: self.display_filename,
display_line_number: self.display_line_number,
#[cfg(feature = "otel")]
make_trace_id: None,
}
}

Expand Down Expand Up @@ -704,6 +754,8 @@ impl<F, T> Format<F, T> {
display_thread_name: self.display_thread_name,
display_filename: self.display_filename,
display_line_number: self.display_line_number,
#[cfg(feature = "otel")]
make_trace_id: None,
}
}

Expand All @@ -720,6 +772,8 @@ impl<F, T> Format<F, T> {
display_thread_name: self.display_thread_name,
display_filename: self.display_filename,
display_line_number: self.display_line_number,
#[cfg(feature = "otel")]
make_trace_id: None,
}
}

Expand Down Expand Up @@ -801,6 +855,15 @@ impl<F, T> Format<F, T> {
.with_file(display_location)
}

/// Set the function to optionally make an OTel `TraceId`.
#[cfg(feature = "otel")]
pub fn with_make_trace_id(self, make_trace_id: Box<dyn MakeTraceId>) -> Self {
Format {
make_trace_id: Some(make_trace_id),
..self
}
}

#[inline]
fn format_timestamp(&self, writer: &mut Writer<'_>) -> fmt::Result
where
Expand Down