opentelemetry/
lib.rs

1//! Implements the [`API`] component of [OpenTelemetry].
2//!
3//! *[Supported Rust Versions](#supported-rust-versions)*
4//!
5//! [`API`]: https://opentelemetry.io/docs/specs/otel/overview/#api
6//! [OpenTelemetry]: https://opentelemetry.io/docs/what-is-opentelemetry/
7//!
8//! # Getting Started with Traces
9//!
10//! The [`trace`] module includes types for tracking the progression of a single
11//! request while it is handled by services that make up an application. A trace
12//! is a tree of [`Span`]s which are objects that represent the work being done
13//! by individual services or components involved in a request as it flows
14//! through a system.
15//!
16//! ```
17//! # #[cfg(feature = "trace")]
18//! # {
19//! use opentelemetry::{global, trace::{Span, Tracer}, KeyValue};
20//!
21//! // get a tracer from a provider
22//! let tracer = global::tracer("my_service");
23//!
24//! // start a new span
25//! let mut span = tracer.start("my_span");
26//!
27//! // set some attributes
28//! span.set_attribute(KeyValue::new("http.client_ip", "83.164.160.102"));
29//!
30//! // perform some more work...
31//!
32//! // end or drop the span to export
33//! span.end();
34//! # }
35//! ```
36//!
37//! See the [examples](https://github.com/open-telemetry/opentelemetry-rust/tree/main/examples) directory for different integration patterns.
38//!
39//! See the [`trace`] module docs for more information on creating and managing
40//! spans.
41//!
42//! [`Span`]: crate::trace::Span
43//!
44//! # Getting Started with Metrics
45//!
46//! The [`metrics`] module provides types for recording measurements about a
47//! service at runtime. Below are the key steps to report measurements using
48//! OpenTelemetry Metrics:
49//!
50//! 1. **Obtain a Meter:** Get a `Meter` from a `MeterProvider`.
51//! 2. **Create Instruments:** Use the `Meter` to create one or more instruments
52//!    (e.g., counters, histograms).
53//! 3. **Record Measurements:** Use the instruments to record measurement values
54//!    along with optional attributes.
55//!
56//! ## How Metrics work in OpenTelemetry
57//! In OpenTelemetry, raw measurements recorded using instruments are
58//! **aggregated in memory** to form metrics. These aggregated metrics are
59//! periodically exported by the [`opentelemetry_sdk`] at fixed intervals (e.g.,
60//! every 60 seconds) via exporters such as [`opentelemetry-stdout`] or
61//! [`opentelemetry-otlp`]. This reduces reporting overhead while ensuring
62//! up-to-date data. The aggregation strategy and export interval can be
63//! customized in the [`opentelemetry_sdk`] based on your use case.
64//!
65//! ## Choosing the Right Instrument
66//! Selecting the correct instrument is critical for accurately representing
67//! your metrics data:
68//!
69//! - Use **Counters** for values that only increase, such as the number of
70//!   requests served or errors encountered.
71//! - Use **UpDownCounters** for values that can increase or decrease, such as
72//!   the number of active connections, number of items in a queue etc.
73//! - **Gauges:** Use for values that can go up or down and represent the
74//!   current state, such as CPU usage, temperature etc.
75//! - Use **Histograms** for measuring the distribution of a value, such as
76//!   response times or payload sizes.
77//!
78//! ### Observable Instruments
79//!
80//! Counters, UpDownCounters, and Gauges have Observable variants that allow
81//! values to be reported through a callback function. Observable instruments
82//! are ideal when the metric value is managed elsewhere and needs to be
83//! observed by OpenTelemetry instrumentation. The callbacks are automatically
84//! invoked by the OpenTelemetry SDK before every export (e.g., every 60
85//! seconds).
86//!
87//! For example:
88//! - An **ObservableCounter** can monitor the number of page faults in a
89//!   process as reported by the operating system.
90//! - An **ObservableUpDownCounter** can monitor the size of an in-memory queue
91//!   by reporting the size using queue's len() method within the callback
92//!   function.
93//! - An **ObservableGauge** can monitor the CPU temperature by using
94//!   temperature sensor APIs within the callback function.
95//!   
96//! For detailed guidance, refer to [OpenTelemetry Metrics API - Instrumentation
97//! Guidance](https://opentelemetry.io/docs/specs/otel/metrics/supplementary-guidelines/#instrument-selection).
98//!
99//! ## Best Practices
100//! - **Re-use Instruments:** Instruments are designed for
101//!   reuse. Avoid creating new instruments repeatedly.
102//! - **Clone for Sharing:** If the same instrument needs to be used across
103//!   multiple parts of your code, you can safely clone it to share.
104//!
105//! ## Example Usage
106//! ```
107//! use opentelemetry::{global, KeyValue};
108//!
109//! // Get a meter from a provider.
110//! let meter = global::meter("my_service");
111//!
112//! // Create an instrument (in this case, a Counter).
113//! let counter = meter.u64_counter("request.count").build();
114//!
115//! // Record a measurement by passing the value and a set of attributes.
116//! counter.add(1, &[KeyValue::new("http.client_ip", "83.164.160.102")]);
117//!
118//! // Create an ObservableCounter and register a callback that reports the measurement.
119//! let _observable_counter = meter
120//! .u64_observable_counter("bytes_received")
121//! .with_callback(|observer| {
122//!     observer.observe(
123//!         100,
124//!         &[
125//!             KeyValue::new("protocol", "udp"),
126//!         ],
127//!     )
128//! })
129//! .build();
130//! ```
131//!
132//! See the
133//! [examples](https://github.com/open-telemetry/opentelemetry-rust/tree/main/examples/metrics-basic)
134//! directory that show a runnable example with all type of instruments.
135//!
136//!
137//! See the [`metrics`] module docs for more information on creating and
138//! managing instruments.
139//!
140//!
141//! # Getting Started with Logs
142//!
143//!  The [`logs`] module contains the Logs Bridge API. It is not intended to be
144//!  called by application developers directly. It is provided for logging
145//!  library authors to build log appenders, that bridges existing logging
146//!  systems with OpenTelemetry. Bridges for
147//!  [`log`](https://crates.io/crates/log) and
148//!  [`tracing`](https://crates.io/crates/tracing) libraries are provided via
149//!  the
150//!  [`opentelemetry-appender-log`](https://crates.io/crates/opentelemetry-appender-log)
151//!  and
152//!  [`opentelemetry-appender-tracing`](https://crates.io/crates/opentelemetry-appender-tracing)
153//!  crates.
154//!
155//! # Crate Feature Flags
156//!
157//! The following core crate feature flags are available:
158//!
159//! * `trace`: Includes the trace API.
160//! * `metrics`: Includes the metrics API.
161//! * `logs`: Includes the logs bridge API.
162//! * `internal-logs`: Includes internal logging for the OpenTelemetry library via `tracing`.
163//!
164//! The default feature flags are ["trace", "metrics", "logs", "internal-logs"].
165//!
166//! The following feature flags provides additional configuration for `logs`:
167//! * `spec_unstable_logs_enabled`: Allow users to control the log level
168//!
169//! The following feature flags enable APIs defined in OpenTelemetry specification that is in experimental phase:
170//! * `otel_unstable`: Includes unstable APIs. There are no features behind this flag at the moment.
171//!
172//! # Related Crates
173//!
174//! In addition to `opentelemetry`, the [`open-telemetry/opentelemetry-rust`]
175//! repository contains several additional crates designed to be used with the
176//! `opentelemetry` ecosystem. This includes exporters, samplers, as well as
177//! utility and adapter crates to assist in propagating context and
178//! instrumenting applications.
179//!
180//! In particular, the following crates are likely to be of interest:
181//!
182//! - [`opentelemetry_sdk`] provides the OpenTelemetry SDK used to configure providers.
183//! - [`opentelemetry-http`] provides an interface for injecting and extracting
184//!   trace information from [`http`] headers.
185//! - [`opentelemetry-otlp`] exporter for sending telemetry in the
186//!   OTLP format.
187//! - [`opentelemetry-stdout`] provides ability to output telemetry to stdout,
188//!   primarily used for learning/debugging purposes.
189//! - [`opentelemetry-prometheus`] provides a pipeline and exporter for sending
190//!   metrics information to [`Prometheus`].
191//! - [`opentelemetry-zipkin`] provides a pipeline and exporter for sending
192//!   trace information to [`Zipkin`].
193//!
194//!  In addition, there are several other useful crates in the [OTel Rust
195//!  Contrib
196//!  repo](https://github.com/open-telemetry/opentelemetry-rust-contrib). A lot
197//!  of crates maintained outside OpenTelemetry owned repos can be found in the
198//!  [OpenTelemetry
199//!  Registry](https://opentelemetry.io/ecosystem/registry/?language=rust).
200//!
201//! [`http`]: https://crates.io/crates/http
202//! [`open-telemetry/opentelemetry-rust`]: https://github.com/open-telemetry/opentelemetry-rust
203//! [`opentelemetry_sdk`]: https://crates.io/crates/opentelemetry_sdk
204//! [`opentelemetry-stdout`]: https://crates.io/crates/opentelemetry_stdout
205//! [`opentelemetry-http`]: https://crates.io/crates/opentelemetry-http
206//! [`opentelemetry-otlp`]: https://crates.io/crates/opentelemetry-otlp
207//! [`opentelemetry-prometheus`]: https://crates.io/crates/opentelemetry-prometheus
208//! [`opentelemetry-zipkin`]: https://crates.io/crates/opentelemetry-zipkin
209//! [`Prometheus`]: https://prometheus.io
210//! [`Zipkin`]: https://zipkin.io
211//!
212//! # Supported Rust Versions
213//!
214//! OpenTelemetry is built against the latest stable release. The minimum
215//! supported version is 1.70. The current OpenTelemetry version is not
216//! guaranteed to build on Rust versions earlier than the minimum supported
217//! version.
218//!
219//! The current stable Rust compiler and the three most recent minor versions
220//! before it will always be supported. For example, if the current stable
221//! compiler version is 1.49, the minimum supported version will not be
222//! increased past 1.46, three minor versions prior. Increasing the minimum
223//! supported compiler version is not considered a semver breaking change as
224//! long as doing so complies with this policy.
225#![warn(
226    future_incompatible,
227    missing_debug_implementations,
228    missing_docs,
229    nonstandard_style,
230    rust_2018_idioms,
231    unreachable_pub,
232    unused
233)]
234#![allow(clippy::needless_doctest_main)]
235#![cfg_attr(
236    docsrs,
237    feature(doc_cfg, doc_auto_cfg),
238    deny(rustdoc::broken_intra_doc_links)
239)]
240#![doc(
241    html_logo_url = "https://raw.githubusercontent.com/open-telemetry/opentelemetry-rust/main/assets/logo.svg"
242)]
243#![cfg_attr(test, deny(warnings))]
244
245pub mod global;
246
247pub mod baggage;
248
249mod context;
250
251pub use context::{Context, ContextGuard};
252
253mod trace_context;
254pub use trace_context::{SpanId, TraceFlags, TraceId};
255
256mod common;
257
258#[cfg(any(feature = "testing", test))]
259#[doc(hidden)]
260pub mod testing;
261
262pub use common::{
263    Array, InstrumentationScope, InstrumentationScopeBuilder, Key, KeyValue, StringValue, Value,
264};
265
266#[cfg(feature = "metrics")]
267#[cfg_attr(docsrs, doc(cfg(feature = "metrics")))]
268pub mod metrics;
269
270#[cfg(feature = "trace")]
271#[cfg_attr(docsrs, doc(cfg(feature = "trace")))]
272pub mod propagation;
273
274#[cfg(feature = "trace")]
275#[cfg_attr(docsrs, doc(cfg(feature = "trace")))]
276pub mod trace;
277
278#[cfg(feature = "logs")]
279#[cfg_attr(docsrs, doc(cfg(feature = "logs")))]
280pub mod logs;
281
282#[doc(hidden)]
283#[cfg(any(feature = "metrics", feature = "trace", feature = "logs"))]
284pub mod time {
285    use std::time::SystemTime;
286
287    #[doc(hidden)]
288    #[cfg(any(
289        not(target_arch = "wasm32"),
290        all(target_arch = "wasm32", target_os = "wasi")
291    ))]
292    pub fn now() -> SystemTime {
293        SystemTime::now()
294    }
295
296    #[doc(hidden)]
297    #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
298    pub fn now() -> SystemTime {
299        SystemTime::UNIX_EPOCH + std::time::Duration::from_millis(js_sys::Date::now() as u64)
300    }
301}