tracing_opentelemetry/lib.rs
1//! # Tracing OpenTelemetry
2//!
3//! [`tracing`] is a framework for instrumenting Rust programs to collect
4//! structured, event-based diagnostic information. This crate provides a layer
5//! that connects spans from multiple systems into a trace and emits them to
6//! [OpenTelemetry]-compatible distributed tracing systems for processing and
7//! visualization.
8//!
9//! [OpenTelemetry]: https://opentelemetry.io
10//! [`tracing`]: https://github.com/tokio-rs/tracing
11//!
12//! ### Special Fields
13//!
14//! Fields with an `otel.` prefix are reserved for this crate and have specific
15//! meaning. They are treated as ordinary fields by other layers. The current
16//! special fields are:
17//!
18//! * `otel.name`: Override the span name sent to OpenTelemetry exporters.
19//! Setting this field is useful if you want to display non-static information
20//! in your span name.
21//! * `otel.kind`: Set the span kind to one of the supported OpenTelemetry [span kinds]. These must
22//! be specified as strings such as `"client"` or `"server"`. If it is not specified, the span is
23//! assumed to be internal.
24//! * `otel.status_code`: Set the span status code to one of the supported OpenTelemetry [span status codes].
25//! * `otel.status_description`: Set the span description of the status. This should be used only if
26//! `otel.status_code` is also set.
27//!
28//! [span kinds]: opentelemetry::trace::SpanKind
29//! [span status codes]: opentelemetry::trace::Status
30//!
31//! ### Semantic Conventions
32//!
33//! OpenTelemetry defines conventional names for attributes of common
34//! operations. These names can be assigned directly as fields, e.g.
35//! `trace_span!("request", "server.port" = 80, "url.full" = ..)`, and they
36//! will be passed through to your configured OpenTelemetry exporter. You can
37//! find the full list of the operations and their expected field names in the
38//! [semantic conventions] spec.
39//!
40//! [semantic conventions]: https://github.com/open-telemetry/semantic-conventions
41//!
42//! ### Stability Status
43//!
44//! The OpenTelemetry tracing specification is stable but the underlying [opentelemetry crate] is
45//! not so some breaking changes will still occur in this crate as well. Metrics are not yet fully
46//! stable. You can read the specification via the [spec repository].
47//!
48//! [opentelemetry crate]: https://github.com/open-telemetry/opentelemetry-rust
49//! [spec repository]: https://github.com/open-telemetry/opentelemetry-specification
50//!
51//! ### OpenTelemetry Logging
52//!
53//! Logging to OpenTelemetry collectors is not supported by this crate, only traces and metrics are.
54//! If you need to export logs through OpenTelemetry, consider [`opentelemetry-appender-tracing`].
55//!
56//! [`opentelemetry-appender-tracing`]: https://crates.io/crates/opentelemetry-appender-tracing
57//!
58//! ## Examples
59//!
60//! ```
61//! use opentelemetry_sdk::trace::SdkTracerProvider;
62//! use opentelemetry::trace::{Tracer, TracerProvider as _};
63//! use tracing::{error, span};
64//! use tracing_subscriber::layer::SubscriberExt;
65//! use tracing_subscriber::Registry;
66//!
67//! // Create a new OpenTelemetry trace pipeline that prints to stdout
68//! let provider = SdkTracerProvider::builder()
69//! .with_simple_exporter(opentelemetry_stdout::SpanExporter::default())
70//! .build();
71//! let tracer = provider.tracer("readme_example");
72//!
73//! // Create a tracing layer with the configured tracer
74//! let telemetry = tracing_opentelemetry::layer().with_tracer(tracer);
75//!
76//! // Use the tracing subscriber `Registry`, or any other subscriber
77//! // that impls `LookupSpan`
78//! let subscriber = Registry::default().with(telemetry);
79//!
80//! // Trace executed code
81//! tracing::subscriber::with_default(subscriber, || {
82//! // Spans will be sent to the configured OpenTelemetry exporter
83//! let root = span!(tracing::Level::TRACE, "app_start", work_units = 2);
84//! let _enter = root.enter();
85//!
86//! error!("This event will be logged in the root span.");
87//! });
88//! ```
89//!
90//! ## Feature Flags
91//!
92//! - `metrics`: Enables the [`MetricsLayer`] type, a [layer] that
93//! exports OpenTelemetry metrics from specifically-named events. This enables
94//! the `metrics` feature flag on the `opentelemetry` crate. *Enabled by
95//! default*.
96//!
97//! [layer]: tracing_subscriber::layer
98#![warn(unreachable_pub)]
99#![doc(
100 html_logo_url = "https://raw.githubusercontent.com/tokio-rs/tracing/master/assets/logo-type.png"
101)]
102#![cfg_attr(
103 docsrs,
104 // Allows displaying cfgs/feature flags in the documentation.
105 feature(doc_cfg),
106 // Allows adding traits to RustDoc's list of "notable traits"
107 feature(doc_notable_trait),
108 // Fail the docs build if any intra-docs links are broken
109 deny(rustdoc::broken_intra_doc_links),
110)]
111
112/// Implementation of the trace::Subscriber trait; publishes OpenTelemetry metrics.
113#[cfg(feature = "metrics")]
114mod metrics;
115
116/// Implementation of the trace::Layer as a source of OpenTelemetry data.
117mod layer;
118/// Function which enables OpenTelemetry context extraction from span extensions.
119mod otel_context;
120/// Span extension which enables OpenTelemetry context management.
121mod span_ext;
122
123mod stack;
124
125use std::{
126 sync::{Arc, Mutex, MutexGuard},
127 time::SystemTime,
128};
129
130pub use layer::{layer, FilteredOpenTelemetryLayer, OpenTelemetryLayer};
131
132#[cfg(feature = "metrics")]
133pub use metrics::MetricsLayer;
134pub use otel_context::get_otel_context;
135pub use span_ext::{OpenTelemetrySpanExt, SetParentError};
136
137#[derive(Debug, Clone)]
138struct OtelDataLock {
139 inner: Arc<Mutex<OtelData>>,
140}
141
142impl OtelDataLock {
143 fn lock(&self) -> MutexGuard<'_, OtelData> {
144 self.inner.lock().expect("otel data lock poisoned")
145 }
146
147 fn new(inner: OtelData) -> Self {
148 Self {
149 inner: Arc::new(Mutex::new(inner)),
150 }
151 }
152}
153
154/// Per-span OpenTelemetry data tracked by this crate.
155#[derive(Debug, Clone)]
156struct OtelData {
157 /// The state of the OtelData, which can either be a builder or a context.
158 state: OtelDataState,
159 /// The end time of the span if it has been exited.
160 end_time: Option<SystemTime>,
161}
162
163/// The state of the OpenTelemetry data for a span.
164#[derive(Debug, Clone)]
165#[allow(clippy::large_enum_variant)]
166pub(crate) enum OtelDataState {
167 /// The span is being built, with a parent context and a builder.
168 Builder {
169 parent_cx: opentelemetry::Context,
170 builder: opentelemetry::trace::SpanBuilder,
171 status: opentelemetry::trace::Status,
172 },
173 /// The span has been started or accessed and is now in a context.
174 Context { current_cx: opentelemetry::Context },
175}
176
177impl Default for OtelDataState {
178 fn default() -> Self {
179 OtelDataState::Context {
180 current_cx: opentelemetry::Context::default(),
181 }
182 }
183}
184
185pub(crate) mod time {
186 use std::time::SystemTime;
187
188 #[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))]
189 pub(crate) fn now() -> SystemTime {
190 SystemTime::now()
191 }
192
193 #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
194 pub(crate) fn now() -> SystemTime {
195 SystemTime::UNIX_EPOCH + std::time::Duration::from_millis(js_sys::Date::now() as u64)
196 }
197}