Skip to main content

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