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//! *Compiler support: [requires `rustc` 1.65+][msrv]*
13//!
14//! [msrv]: #supported-rust-versions
15//!
16//! ### Special Fields
17//!
18//! Fields with an `otel.` prefix are reserved for this crate and have specific
19//! meaning. They are treated as ordinary fields by other layers. The current
20//! special fields are:
21//!
22//! * `otel.name`: Override the span name sent to OpenTelemetry exporters.
23//! Setting this field is useful if you want to display non-static information
24//! in your span name.
25//! * `otel.kind`: Set the span kind to one of the supported OpenTelemetry [span kinds].
26//! * `otel.status_code`: Set the span status code to one of the supported OpenTelemetry [span status codes].
27//! * `otel.status_message`: Set the span status message.
28//!
29//! [span kinds]: opentelemetry::trace::SpanKind
30//! [span status codes]: opentelemetry::trace::Status
31//!
32//! ### Semantic Conventions
33//!
34//! OpenTelemetry defines conventional names for attributes of common
35//! operations. These names can be assigned directly as fields, e.g.
36//! `trace_span!("request", "otel.kind" = %SpanKind::Client, "url.full" = ..)`, and they
37//! will be passed through to your configured OpenTelemetry exporter. You can
38//! find the full list of the operations and their expected field names in the
39//! [semantic conventions] spec.
40//!
41//! [semantic conventions]: https://github.com/open-telemetry/semantic-conventions
42//!
43//! ### Stability Status
44//!
45//! The OpenTelemetry specification is currently in beta so some breaking
46//! changes may still occur on the path to 1.0. You can follow the changes via
47//! the [spec repository] to track progress toward stabilization.
48//!
49//! [spec repository]: https://github.com/open-telemetry/opentelemetry-specification
50//!
51//! ## Examples
52//!
53//! ```
54//! use opentelemetry_sdk::trace::TracerProvider;
55//! use opentelemetry::trace::{Tracer, TracerProvider as _};
56//! use tracing::{error, span};
57//! use tracing_subscriber::layer::SubscriberExt;
58//! use tracing_subscriber::Registry;
59//!
60//! // Create a new OpenTelemetry trace pipeline that prints to stdout
61//! let provider = TracerProvider::builder()
62//!     .with_simple_exporter(opentelemetry_stdout::SpanExporter::default())
63//!     .build();
64//! let tracer = provider.tracer("readme_example");
65//!
66//! // Create a tracing layer with the configured tracer
67//! let telemetry = tracing_opentelemetry::layer().with_tracer(tracer);
68//!
69//! // Use the tracing subscriber `Registry`, or any other subscriber
70//! // that impls `LookupSpan`
71//! let subscriber = Registry::default().with(telemetry);
72//!
73//! // Trace executed code
74//! tracing::subscriber::with_default(subscriber, || {
75//!     // Spans will be sent to the configured OpenTelemetry exporter
76//!     let root = span!(tracing::Level::TRACE, "app_start", work_units = 2);
77//!     let _enter = root.enter();
78//!
79//!     error!("This event will be logged in the root span.");
80//! });
81//! ```
82//!
83//! ## Feature Flags
84//!
85//! - `metrics`: Enables the [`MetricsLayer`] type, a [layer] that
86//!   exports OpenTelemetry metrics from specifically-named events. This enables
87//!   the `metrics` feature flag on the `opentelemetry` crate.  *Enabled by
88//!   default*.
89//!
90//! [layer]: tracing_subscriber::layer
91//!
92//! ## Supported Rust Versions
93//!
94//! Tracing is built against the latest stable release. The minimum supported
95//! version is 1.60. The current Tracing version is not guaranteed to build on
96//! Rust versions earlier than the minimum supported version.
97//!
98//! Tracing follows the same compiler support policies as the rest of the Tokio
99//! project. The current stable Rust compiler and the three most recent minor
100//! versions before it will always be supported. For example, if the current
101//! stable compiler version is 1.45, the minimum supported version will not be
102//! increased past 1.42, three minor versions prior. Increasing the minimum
103//! supported compiler version is not considered a semver breaking change as
104//! long as doing so complies with this policy.
105//!
106//! [subscriber]: tracing_subscriber::subscribe
107#![deny(unreachable_pub)]
108#![cfg_attr(test, deny(warnings))]
109#![doc(html_root_url = "https://docs.rs/tracing-opentelemetry/0.22.0")]
110#![doc(
111    html_logo_url = "https://raw.githubusercontent.com/tokio-rs/tracing/master/assets/logo-type.png",
112    issue_tracker_base_url = "https://github.com/tokio-rs/tracing-opentelemetry/issues/"
113)]
114#![cfg_attr(
115    docsrs,
116    // Allows displaying cfgs/feature flags in the documentation.
117    feature(doc_cfg, doc_auto_cfg),
118    // Allows adding traits to RustDoc's list of "notable traits"
119    feature(doc_notable_trait),
120    // Fail the docs build if any intra-docs links are broken
121    deny(rustdoc::broken_intra_doc_links),
122)]
123
124/// Implementation of the trace::Subscriber trait; publishes OpenTelemetry metrics.
125#[cfg(feature = "metrics")]
126mod metrics;
127
128/// Implementation of the trace::Layer as a source of OpenTelemetry data.
129mod layer;
130/// Span extension which enables OpenTelemetry context management.
131mod span_ext;
132/// Protocols for OpenTelemetry Tracers that are compatible with Tracing
133mod tracer;
134
135pub use layer::{layer, OpenTelemetryLayer};
136
137#[cfg(feature = "metrics")]
138pub use metrics::MetricsLayer;
139pub use span_ext::OpenTelemetrySpanExt;
140pub use tracer::PreSampledTracer;
141
142/// Per-span OpenTelemetry data tracked by this crate.
143///
144/// Useful for implementing [PreSampledTracer] in alternate otel SDKs.
145#[derive(Debug, Clone)]
146pub struct OtelData {
147    /// The parent otel `Context` for the current tracing span.
148    pub parent_cx: opentelemetry::Context,
149
150    /// The otel span data recorded during the current tracing span.
151    pub builder: opentelemetry::trace::SpanBuilder,
152}
153
154pub(crate) mod time {
155    use std::time::SystemTime;
156
157    #[cfg(not(all(target_arch = "wasm32", not(target_os = "wasi"))))]
158    pub(crate) fn now() -> SystemTime {
159        SystemTime::now()
160    }
161
162    #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
163    pub(crate) fn now() -> SystemTime {
164        SystemTime::UNIX_EPOCH + std::time::Duration::from_millis(js_sys::Date::now() as u64)
165    }
166}