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/// Span extension which enables OpenTelemetry context management.
119mod span_ext;
120
121mod stack;
122
123use std::time::SystemTime;
124
125pub use layer::{layer, OpenTelemetryLayer};
126
127#[cfg(feature = "metrics")]
128pub use metrics::MetricsLayer;
129use opentelemetry::trace::TraceContextExt as _;
130pub use span_ext::OpenTelemetrySpanExt;
131
132/// Per-span OpenTelemetry data tracked by this crate.
133#[derive(Debug)]
134pub struct OtelData {
135 /// The state of the OtelData, which can either be a builder or a context.
136 state: OtelDataState,
137 /// The end time of the span if it has been exited.
138 end_time: Option<SystemTime>,
139}
140
141impl OtelData {
142 /// Gets the trace ID of the span.
143 ///
144 /// Returns `None` if the context has not been built yet. This can be forced e.g. by calling
145 /// [`context`] on the span (not on `OtelData`) or if [context activation] was not explicitly
146 /// opted-out of, simply entering the span for the first time.
147 ///
148 /// [`context`]: OpenTelemetrySpanExt::context
149 /// [context activation]: OpenTelemetryLayer::with_context_activation
150 pub fn trace_id(&self) -> Option<opentelemetry::TraceId> {
151 if let OtelDataState::Context { current_cx } = &self.state {
152 Some(current_cx.span().span_context().trace_id())
153 } else {
154 None
155 }
156 }
157
158 /// Gets the span ID of the span.
159 ///
160 /// Returns `None` if the context has not been built yet. This can be forced e.g. by calling
161 /// [`context`] on the span (not on `OtelData`) or if [context activation] was not explicitly
162 /// opted-out of, simply entering the span for the first time.
163 ///
164 /// [`context`]: OpenTelemetrySpanExt::context
165 /// [context activation]: OpenTelemetryLayer::with_context_activation
166 pub fn span_id(&self) -> Option<opentelemetry::SpanId> {
167 if let OtelDataState::Context { current_cx } = &self.state {
168 Some(current_cx.span().span_context().span_id())
169 } else {
170 None
171 }
172 }
173}
174
175/// The state of the OpenTelemetry data for a span.
176#[derive(Debug)]
177#[allow(clippy::large_enum_variant)]
178pub(crate) enum OtelDataState {
179 /// The span is being built, with a parent context and a builder.
180 Builder {
181 parent_cx: opentelemetry::Context,
182 builder: opentelemetry::trace::SpanBuilder,
183 },
184 /// The span has been started or accessed and is now in a context.
185 Context { current_cx: opentelemetry::Context },
186}
187
188impl Default for OtelDataState {
189 fn default() -> Self {
190 OtelDataState::Context {
191 current_cx: opentelemetry::Context::default(),
192 }
193 }
194}
195
196pub(crate) mod time {
197 use std::time::SystemTime;
198
199 #[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))]
200 pub(crate) fn now() -> SystemTime {
201 SystemTime::now()
202 }
203
204 #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
205 pub(crate) fn now() -> SystemTime {
206 SystemTime::UNIX_EPOCH + std::time::Duration::from_millis(js_sys::Date::now() as u64)
207 }
208}