opentelemetry_otlp/lib.rs
1//! # OpenTelemetry OTLP Exporter
2//!
3//! The OTLP Exporter enables exporting telemetry data (logs, metrics, and traces) in the
4//! OpenTelemetry Protocol (OTLP) format to compatible backends. These backends include:
5//!
6//! - OpenTelemetry Collector
7//! - Open-source observability tools (Prometheus, Jaeger, etc.)
8//! - Vendor-specific monitoring platforms
9//!
10//! This crate supports sending OTLP data via:
11//! - gRPC
12//! - HTTP (binary protobuf or JSON)
13//!
14//! ## Quickstart with OpenTelemetry Collector
15//!
16//! ### HTTP Transport (Port 4318)
17//!
18//! Run the OpenTelemetry Collector:
19//!
20//! ```shell
21//! $ docker run -p 4318:4318 otel/opentelemetry-collector:latest
22//! ```
23//!
24//! Configure your application to export traces via HTTP:
25//!
26//! ```no_run
27//! # #[cfg(all(feature = "trace", feature = "http-proto"))]
28//! # {
29//! use opentelemetry::global;
30//! use opentelemetry::trace::Tracer;
31//! use opentelemetry_otlp::Protocol;
32//! use opentelemetry_otlp::WithExportConfig;
33//!
34//! fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
35//! // Initialize OTLP exporter using HTTP binary protocol
36//! let otlp_exporter = opentelemetry_otlp::SpanExporter::builder()
37//! .with_http()
38//! .with_protocol(Protocol::HttpBinary)
39//! .build()?;
40//!
41//! // Create a tracer provider with the exporter
42//! let tracer_provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
43//! .with_batch_exporter(otlp_exporter)
44//! .build();
45//!
46//! // Set it as the global provider
47//! global::set_tracer_provider(tracer_provider);
48//!
49//! // Get a tracer and create spans
50//! let tracer = global::tracer("my_tracer");
51//! tracer.in_span("doing_work", |_cx| {
52//! // Your application logic here...
53//! });
54//!
55//! Ok(())
56//! # }
57//! }
58//! ```
59//!
60//! ### gRPC Transport (Port 4317)
61//!
62//! Run the OpenTelemetry Collector:
63//!
64//! ```shell
65//! $ docker run -p 4317:4317 otel/opentelemetry-collector:latest
66//! ```
67//!
68//! Configure your application to export traces via gRPC (the tonic client requires a Tokio runtime):
69//!
70//! - With `[tokio::main]`
71//!
72//! ```no_run
73//! # #[cfg(all(feature = "trace", feature = "grpc-tonic"))]
74//! # {
75//! use opentelemetry::{global, trace::Tracer};
76//!
77//! #[tokio::main]
78//! async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
79//! // Initialize OTLP exporter using gRPC (Tonic)
80//! let otlp_exporter = opentelemetry_otlp::SpanExporter::builder()
81//! .with_tonic()
82//! .build()?;
83//!
84//! // Create a tracer provider with the exporter
85//! let tracer_provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
86//! .with_batch_exporter(otlp_exporter)
87//! .build();
88//!
89//! // Set it as the global provider
90//! global::set_tracer_provider(tracer_provider);
91//!
92//! // Get a tracer and create spans
93//! let tracer = global::tracer("my_tracer");
94//! tracer.in_span("doing_work", |_cx| {
95//! // Your application logic here...
96//! });
97//!
98//! Ok(())
99//! # }
100//! }
101//! ```
102//!
103//! - Without `[tokio::main]`
104//!
105//! ```no_run
106//! # #[cfg(all(feature = "trace", feature = "grpc-tonic"))]
107//! # {
108//! use opentelemetry::{global, trace::Tracer};
109//!
110//! fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
111//! // Initialize OTLP exporter using gRPC (Tonic)
112//! let rt = tokio::runtime::Runtime::new()?;
113//! let tracer_provider = rt.block_on(async {
114//! let exporter = opentelemetry_otlp::SpanExporter::builder()
115//! .with_tonic()
116//! .build()
117//! .expect("Failed to create span exporter");
118//! opentelemetry_sdk::trace::SdkTracerProvider::builder()
119//! .with_batch_exporter(exporter)
120//! .build()
121//! });
122//!
123//! // Set it as the global provider
124//! global::set_tracer_provider(tracer_provider);
125//!
126//! // Get a tracer and create spans
127//! let tracer = global::tracer("my_tracer");
128//! tracer.in_span("doing_work", |_cx| {
129//! // Your application logic here...
130//! });
131//!
132//! // Ensure the runtime (`rt`) remains active until the program ends
133//! Ok(())
134//! # }
135//! }
136//! ```
137//!
138//! ## Using with Jaeger
139//!
140//! Jaeger natively supports the OTLP protocol, making it easy to send traces directly:
141//!
142//! ```shell
143//! $ docker run -p 16686:16686 -p 4317:4317 -e COLLECTOR_OTLP_ENABLED=true jaegertracing/all-in-one:latest
144//! ```
145//!
146//! After running your application configured with the OTLP exporter, view traces at:
147//! `http://localhost:16686`
148//!
149//! ## Using with Prometheus
150//!
151//! Prometheus natively supports accepting metrics via the OTLP protocol
152//! (HTTP/protobuf). You can [run
153//! Prometheus](https://prometheus.io/docs/prometheus/latest/installation/) with
154//! the following command:
155//!
156//! ```shell
157//! docker run -p 9090:9090 -v ./prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus --config.file=/etc/prometheus/prometheus.yml --web.enable-otlp-receiver
158//! ```
159//!
160//! (An empty prometheus.yml file is sufficient for this example.)
161//!
162//! Modify your application to export metrics via OTLP:
163//!
164//! ```no_run
165//! # #[cfg(all(feature = "metrics", feature = "http-proto"))]
166//! # {
167//! use opentelemetry::global;
168//! use opentelemetry::metrics::Meter;
169//! use opentelemetry::KeyValue;
170//! use opentelemetry_otlp::Protocol;
171//! use opentelemetry_otlp::WithExportConfig;
172//!
173//! fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
174//! // Initialize OTLP exporter using HTTP binary protocol
175//! let exporter = opentelemetry_otlp::MetricExporter::builder()
176//! .with_http()
177//! .with_protocol(Protocol::HttpBinary)
178//! .with_endpoint("http://localhost:9090/api/v1/otlp/v1/metrics")
179//! .build()?;
180//!
181//! // Create a meter provider with the OTLP Metric exporter
182//! let meter_provider = opentelemetry_sdk::metrics::SdkMeterProvider::builder()
183//! .with_periodic_exporter(exporter)
184//! .build();
185//! global::set_meter_provider(meter_provider.clone());
186//!
187//! // Get a meter
188//! let meter = global::meter("my_meter");
189//!
190//! // Create a metric
191//! let counter = meter.u64_counter("my_counter").build();
192//! counter.add(1, &[KeyValue::new("key", "value")]);
193//!
194//! // Shutdown the meter provider. This will trigger an export of all metrics.
195//! meter_provider.shutdown()?;
196//!
197//! Ok(())
198//! # }
199//! }
200//! ```
201//!
202//! After running your application configured with the OTLP exporter, view metrics at:
203//! `http://localhost:9090`
204//! ## Show Logs, Metrics too (TODO)
205//!
206//! [`tokio`]: https://tokio.rs
207//!
208//! # Feature Flags
209//! The following feature flags can enable exporters for different telemetry signals:
210//!
211//! * `trace`: Includes the trace exporters.
212//! * `metrics`: Includes the metrics exporters.
213//! * `logs`: Includes the logs exporters.
214//!
215//! The following feature flags generate additional code and types:
216//! * `serialize`: Enables serialization support for type defined in this crate via `serde`.
217//!
218//! The following feature flags offer additional configurations on gRPC:
219//!
220//! For users using `tonic` as grpc layer:
221//! * `grpc-tonic`: Use `tonic` as grpc layer.
222//! * `gzip-tonic`: Use gzip compression for `tonic` grpc layer.
223//! * `zstd-tonic`: Use zstd compression for `tonic` grpc layer.
224//! * `tls-roots`: Adds system trust roots to rustls-based gRPC clients using the rustls-native-certs crate
225//! * `tls-webpki-roots`: Embeds Mozilla's trust roots to rustls-based gRPC clients using the webpki-roots crate
226//!
227//! The following feature flags offer additional configurations on http:
228//!
229//! * `http-proto`: Use http as transport layer, protobuf as body format. This feature is enabled by default.
230//! * `gzip-http`: Use gzip compression for HTTP transport.
231//! * `zstd-http`: Use zstd compression for HTTP transport.
232//! * `reqwest-blocking-client`: Use reqwest blocking http client. This feature is enabled by default.
233//! * `reqwest-client`: Use reqwest http client.
234//! * `reqwest-rustls`: Use reqwest with TLS with system trust roots via `rustls-native-certs` crate.
235//! * `reqwest-rustls-webpki-roots`: Use reqwest with TLS with Mozilla's trust roots via `webpki-roots` crate.
236//!
237//! # Kitchen Sink Full Configuration
238//!
239//! Example showing how to override all configuration options.
240//!
241//! Generally there are two parts of configuration. One is the exporter, the other is the provider.
242//! Users can configure the exporter using [SpanExporter::builder()] for traces,
243//! and [MetricExporter::builder()] + [opentelemetry_sdk::metrics::PeriodicReader::builder()] for metrics.
244//! Once you have an exporter, you can add it to either a [opentelemetry_sdk::trace::SdkTracerProvider::builder()] for traces,
245//! or [opentelemetry_sdk::metrics::SdkMeterProvider::builder()] for metrics.
246//!
247//! ```no_run
248//! use opentelemetry::{global, KeyValue, trace::Tracer};
249//! use opentelemetry_sdk::{trace::{self, RandomIdGenerator, Sampler}, Resource};
250//! # #[cfg(feature = "metrics")]
251//! use opentelemetry_sdk::metrics::Temporality;
252//! use opentelemetry_otlp::{Protocol, WithExportConfig, Compression};
253//! # #[cfg(feature = "grpc-tonic")]
254//! use opentelemetry_otlp::WithTonicConfig;
255//! # #[cfg(any(feature = "http-proto", feature = "http-json"))]
256//! use opentelemetry_otlp::WithHttpConfig;
257//! use std::time::Duration;
258//! # #[cfg(feature = "grpc-tonic")]
259//! use tonic::metadata::*;
260//!
261//! fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
262//! # #[cfg(all(feature = "trace", feature = "grpc-tonic"))]
263//! # let tracer = {
264//! let mut map = MetadataMap::with_capacity(3);
265//!
266//! map.insert("x-host", "example.com".parse().unwrap());
267//! map.insert("x-number", "123".parse().unwrap());
268//! map.insert_bin("trace-proto-bin", MetadataValue::from_bytes(b"[binary data]"));
269//! let exporter = opentelemetry_otlp::SpanExporter::builder()
270//! .with_tonic()
271//! .with_endpoint("http://localhost:4317")
272//! .with_timeout(Duration::from_secs(3))
273//! .with_metadata(map)
274//! .build()?;
275//!
276//! let tracer_provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
277//! .with_batch_exporter(exporter)
278//! .with_sampler(Sampler::AlwaysOn)
279//! .with_id_generator(RandomIdGenerator::default())
280//! .with_max_events_per_span(64)
281//! .with_max_attributes_per_span(16)
282//! .with_resource(Resource::builder_empty().with_attributes([KeyValue::new("service.name", "example")]).build())
283//! .build();
284//! global::set_tracer_provider(tracer_provider.clone());
285//! let tracer = global::tracer("tracer-name");
286//! # tracer
287//! # };
288//!
289//! // HTTP exporter example with compression
290//! # #[cfg(all(feature = "trace", feature = "http-proto"))]
291//! # let _http_tracer = {
292//! let exporter = opentelemetry_otlp::SpanExporter::builder()
293//! .with_http()
294//! .with_endpoint("http://localhost:4318/v1/traces")
295//! .with_timeout(Duration::from_secs(3))
296//! .with_protocol(Protocol::HttpBinary)
297//! .with_compression(Compression::Gzip) // Requires gzip-http feature
298//! .build()?;
299//! # exporter
300//! # };
301//!
302//! # #[cfg(all(feature = "metrics", feature = "grpc-tonic"))]
303//! # {
304//! let exporter = opentelemetry_otlp::MetricExporter::builder()
305//! .with_tonic()
306//! .with_endpoint("http://localhost:4318/v1/metrics")
307//! .with_protocol(Protocol::Grpc)
308//! .with_timeout(Duration::from_secs(3))
309//! .build()
310//! .unwrap();
311//!
312//! let provider = opentelemetry_sdk::metrics::SdkMeterProvider::builder()
313//! .with_periodic_exporter(exporter)
314//! .with_resource(Resource::builder_empty().with_attributes([KeyValue::new("service.name", "example")]).build())
315//! .build();
316//! # }
317//!
318//! // HTTP metrics exporter example with compression
319//! # #[cfg(all(feature = "metrics", feature = "http-proto"))]
320//! # {
321//! let exporter = opentelemetry_otlp::MetricExporter::builder()
322//! .with_http()
323//! .with_endpoint("http://localhost:4318/v1/metrics")
324//! .with_protocol(Protocol::HttpBinary)
325//! .with_timeout(Duration::from_secs(3))
326//! .with_compression(Compression::Zstd) // Requires zstd-http feature
327//! .build()
328//! .unwrap();
329//! # }
330//!
331//! # #[cfg(all(feature = "trace", feature = "grpc-tonic"))]
332//! # {
333//! tracer.in_span("doing_work", |cx| {
334//! // Traced app logic here...
335//! });
336//! # }
337//!
338//! Ok(())
339//! }
340//! ```
341#![warn(
342 future_incompatible,
343 missing_debug_implementations,
344 missing_docs,
345 nonstandard_style,
346 rust_2018_idioms,
347 unreachable_pub,
348 unused
349)]
350#![allow(elided_lifetimes_in_paths)]
351#![cfg_attr(
352 docsrs,
353 feature(doc_cfg, doc_auto_cfg),
354 deny(rustdoc::broken_intra_doc_links)
355)]
356#![cfg_attr(test, deny(warnings))]
357
358mod exporter;
359#[cfg(feature = "logs")]
360#[cfg(any(feature = "http-proto", feature = "http-json", feature = "grpc-tonic"))]
361mod logs;
362#[cfg(feature = "metrics")]
363#[cfg(any(feature = "http-proto", feature = "http-json", feature = "grpc-tonic"))]
364mod metric;
365#[cfg(feature = "trace")]
366#[cfg(any(feature = "http-proto", feature = "http-json", feature = "grpc-tonic"))]
367mod span;
368
369pub use crate::exporter::Compression;
370pub use crate::exporter::ExportConfig;
371pub use crate::exporter::ExporterBuildError;
372#[cfg(feature = "trace")]
373#[cfg(any(feature = "http-proto", feature = "http-json", feature = "grpc-tonic"))]
374pub use crate::span::{
375 SpanExporter, SpanExporterBuilder, OTEL_EXPORTER_OTLP_TRACES_COMPRESSION,
376 OTEL_EXPORTER_OTLP_TRACES_ENDPOINT, OTEL_EXPORTER_OTLP_TRACES_HEADERS,
377 OTEL_EXPORTER_OTLP_TRACES_TIMEOUT,
378};
379
380#[cfg(feature = "metrics")]
381#[cfg(any(feature = "http-proto", feature = "http-json", feature = "grpc-tonic"))]
382pub use crate::metric::{
383 MetricExporter, MetricExporterBuilder, OTEL_EXPORTER_OTLP_METRICS_COMPRESSION,
384 OTEL_EXPORTER_OTLP_METRICS_ENDPOINT, OTEL_EXPORTER_OTLP_METRICS_HEADERS,
385 OTEL_EXPORTER_OTLP_METRICS_TIMEOUT,
386};
387
388#[cfg(feature = "logs")]
389#[cfg(any(feature = "http-proto", feature = "http-json", feature = "grpc-tonic"))]
390pub use crate::logs::{
391 LogExporter, LogExporterBuilder, OTEL_EXPORTER_OTLP_LOGS_COMPRESSION,
392 OTEL_EXPORTER_OTLP_LOGS_ENDPOINT, OTEL_EXPORTER_OTLP_LOGS_HEADERS,
393 OTEL_EXPORTER_OTLP_LOGS_TIMEOUT,
394};
395
396#[cfg(any(feature = "http-proto", feature = "http-json"))]
397pub use crate::exporter::http::{HasHttpConfig, WithHttpConfig};
398
399#[cfg(feature = "grpc-tonic")]
400pub use crate::exporter::tonic::{HasTonicConfig, WithTonicConfig};
401
402pub use crate::exporter::{
403 HasExportConfig, WithExportConfig, OTEL_EXPORTER_OTLP_COMPRESSION, OTEL_EXPORTER_OTLP_ENDPOINT,
404 OTEL_EXPORTER_OTLP_ENDPOINT_DEFAULT, OTEL_EXPORTER_OTLP_HEADERS, OTEL_EXPORTER_OTLP_PROTOCOL,
405 OTEL_EXPORTER_OTLP_PROTOCOL_DEFAULT, OTEL_EXPORTER_OTLP_TIMEOUT,
406 OTEL_EXPORTER_OTLP_TIMEOUT_DEFAULT,
407};
408
409/// Type to indicate the builder does not have a client set.
410#[derive(Debug, Default, Clone)]
411pub struct NoExporterBuilderSet;
412
413/// Type to hold the [TonicExporterBuilder] and indicate it has been set.
414///
415/// Allowing access to [TonicExporterBuilder] specific configuration methods.
416#[cfg(feature = "grpc-tonic")]
417// This is for clippy to work with only the grpc-tonic feature enabled
418#[allow(unused)]
419#[derive(Debug, Default)]
420pub struct TonicExporterBuilderSet(TonicExporterBuilder);
421
422/// Type to hold the [HttpExporterBuilder] and indicate it has been set.
423///
424/// Allowing access to [HttpExporterBuilder] specific configuration methods.
425#[cfg(any(feature = "http-proto", feature = "http-json"))]
426#[derive(Debug, Default)]
427pub struct HttpExporterBuilderSet(HttpExporterBuilder);
428
429#[cfg(any(feature = "http-proto", feature = "http-json"))]
430pub use crate::exporter::http::HttpExporterBuilder;
431
432#[cfg(feature = "grpc-tonic")]
433pub use crate::exporter::tonic::{TonicConfig, TonicExporterBuilder};
434
435#[cfg(feature = "serialize")]
436use serde::{Deserialize, Serialize};
437
438/// The communication protocol to use when exporting data.
439#[cfg_attr(feature = "serialize", derive(Deserialize, Serialize))]
440#[derive(Clone, Copy, Debug, Eq, PartialEq)]
441pub enum Protocol {
442 /// GRPC protocol
443 Grpc,
444 /// HTTP protocol with binary protobuf
445 HttpBinary,
446 /// HTTP protocol with JSON payload
447 HttpJson,
448}
449
450#[derive(Debug, Default)]
451#[doc(hidden)]
452/// Placeholder type when no exporter pipeline has been configured in telemetry pipeline.
453pub struct NoExporterConfig(());
454
455/// Re-exported types from the `tonic` crate.
456#[cfg(feature = "grpc-tonic")]
457pub mod tonic_types {
458 /// Re-exported types from `tonic::metadata`.
459 pub mod metadata {
460 #[doc(no_inline)]
461 pub use tonic::metadata::MetadataMap;
462 }
463
464 /// Re-exported types from `tonic::transport`.
465 #[cfg(feature = "tls")]
466 pub mod transport {
467 #[doc(no_inline)]
468 pub use tonic::transport::{Certificate, ClientTlsConfig, Identity};
469 }
470}