Skip to main content

telemetry_rust/
lib.rs

1#![warn(missing_docs, clippy::missing_panics_doc)]
2
3//! A comprehensive OpenTelemetry telemetry library for Rust applications.
4//!
5//! This crate provides easy-to-use telemetry integration for Rust applications, with support for
6//! OpenTelemetry tracing, metrics, and logging. It includes middleware for popular frameworks
7//! like Axum and AWS Lambda, along with utilities for context propagation and configuration.
8//!
9//! # Features
10//!
11//! - OpenTelemetry tracing instrumentation
12//! - Formatted logs with tracing metadata
13//! - Context Propagation for incoming and outgoing HTTP requests
14//! - Axum middleware to instrument http services
15//! - AWS Lambda instrumentation layer
16//! - AWS SDK instrumentation with automatic attribute extraction
17//! - Integration testing tools
18//!
19//! # Available Feature Flags
20//!
21//! ## Core Features
22//! - `axum`: Axum web framework middleware support
23//! - `test`: Testing utilities for OpenTelemetry validation
24//! - `zipkin`: Zipkin context propagation support (enabled by default)
25//! - `xray`: AWS X-Ray context propagation support
26//! - `future`: Future instrumentation utilities (mostly used internally)
27//!
28//! ## AWS Features
29//! - `aws-span`: AWS SDK span creation utilities
30//! - `aws-instrumentation`: Lightweight manual instrumentation for AWS SDK operations
31//! - `aws-stream-instrumentation`: Instrumentation for AWS SDK pagination streams
32//! - `aws-fluent-builder-instrumentation`: Core traits for fluent builders instrumentation (see [service-specific features](#aws-service-specific-features))
33//! - `aws-lambda`: AWS Lambda runtime middleware
34//!
35//! ## AWS Service-Specific Features
36//! - `aws-dynamodb`: DynamoDB automatic fluent builders instrumentation
37//! - `aws-firehose`: Firehose automatic fluent builders instrumentation
38//! - `aws-s3`: S3 automatic fluent builders instrumentation
39//! - `aws-sns`: SNS automatic fluent builders instrumentation
40//! - `aws-sqs`: SQS automatic fluent builders instrumentation
41//! - `aws-sagemaker-runtime`: SageMaker Runtime automatic fluent builders instrumentation
42//! - `aws-secretsmanager`: Secrets Manager automatic fluent builders instrumentation
43//! - `aws-ssm`: SSM Parameter Store automatic fluent builders instrumentation
44//!
45//! ## Feature Bundles
46//! - `aws`: All core AWS features (span + instrumentation + stream instrumentation)
47//! - `aws-full`: All AWS features including Lambda, all service-specific instrumentations, and X-Ray propagation
48//! - `full`: All features enabled
49//!
50//! # Quick Start
51//!
52//! ```rust
53//! use telemetry_rust::{init_tracing, shutdown_tracer_provider};
54//! use tracing::Level;
55//!
56//! // Initialize telemetry
57//! let tracer_provider = init_tracing!(Level::INFO);
58//!
59//! // Your application code here...
60//!
61//! // Shutdown telemetry when done
62//! shutdown_tracer_provider(&tracer_provider);
63//! ```
64
65// Initialization logic was retired from https://github.com/davidB/tracing-opentelemetry-instrumentation-sdk/
66// which is licensed under CC0 1.0 Universal
67// https://github.com/davidB/tracing-opentelemetry-instrumentation-sdk/blob/d3609ac2cc699d3a24fbf89754053cc8e938e3bf/LICENSE
68
69use tracing::level_filters::LevelFilter;
70#[cfg(debug_assertions)]
71use tracing_subscriber::fmt::format::FmtSpan;
72use tracing_subscriber::layer::SubscriberExt;
73
74use opentelemetry::trace::TracerProvider as _;
75pub use opentelemetry::{Array, Context, Key, KeyValue, StringValue, Value, global};
76pub use opentelemetry_sdk::{
77    Resource,
78    error::OTelSdkError,
79    resource::{EnvResourceDetector, ResourceDetector, TelemetryResourceDetector},
80    trace::SdkTracerProvider as TracerProvider,
81};
82pub use opentelemetry_semantic_conventions::attribute as semconv;
83pub use tracing_opentelemetry::{OpenTelemetryLayer, OpenTelemetrySpanExt};
84
85pub mod fmt;
86pub mod http;
87pub mod middleware;
88pub mod otlp;
89pub mod propagation;
90
91#[cfg(feature = "axum")]
92pub use tracing_opentelemetry_instrumentation_sdk;
93
94#[cfg(feature = "test")]
95pub mod test;
96
97#[cfg(feature = "future")]
98pub mod future;
99
100mod filter;
101mod util;
102
103/// Resource detection utility for automatically configuring OpenTelemetry service metadata.
104///
105/// This struct helps detect and configure service information from environment variables
106/// with fallback values. It supports the standard OpenTelemetry environment variables
107/// as well as common service naming conventions.
108///
109/// # Environment Variables
110///
111/// The following environment variables are checked in order of priority:
112/// - Service name: `OTEL_SERVICE_NAME`, service.name from `OTEL_RESOURCE_ATTRIBUTES`, `SERVICE_NAME`, `APP_NAME`
113/// - Service version: `OTEL_SERVICE_VERSION`, service.version from `OTEL_RESOURCE_ATTRIBUTES`, `SERVICE_VERSION`, `APP_VERSION`
114///
115/// Note: `OTEL_RESOURCE_ATTRIBUTES` is automatically parsed by the OpenTelemetry SDK's environment resource detector.
116#[derive(Debug, Default)]
117pub struct DetectResource {
118    fallback_service_name: &'static str,
119    fallback_service_version: &'static str,
120}
121
122impl DetectResource {
123    /// Creates a new `DetectResource` with the provided fallback service name and version.
124    ///
125    /// # Arguments
126    ///
127    /// * `fallback_service_name` - The default service name to use if not found in environment variables.
128    /// * `fallback_service_version` - The default service version to use if not found in environment variables.
129    pub fn new(
130        fallback_service_name: &'static str,
131        fallback_service_version: &'static str,
132    ) -> Self {
133        DetectResource {
134            fallback_service_name,
135            fallback_service_version,
136        }
137    }
138
139    /// Builds the OpenTelemetry resource with detected service information.
140    ///
141    /// This method checks environment variables in order of priority and falls back
142    /// to the provided default values if no environment variables are set.
143    ///
144    /// # Returns
145    ///
146    /// A configured [`Resource`] with service name and version attributes.
147    pub fn build(self) -> Resource {
148        let env_detector = EnvResourceDetector::new();
149        let env_resource = env_detector.detect();
150
151        let read_from_env = |key| util::env_var(key).map(Into::into);
152
153        let service_name_key = Key::new(semconv::SERVICE_NAME);
154        let service_name_value = read_from_env("OTEL_SERVICE_NAME")
155            .or_else(|| env_resource.get(&service_name_key))
156            .or_else(|| read_from_env("SERVICE_NAME"))
157            .or_else(|| read_from_env("APP_NAME"))
158            .unwrap_or_else(|| self.fallback_service_name.into());
159
160        let service_version_key = Key::new(semconv::SERVICE_VERSION);
161        let service_version_value = read_from_env("OTEL_SERVICE_VERSION")
162            .or_else(|| env_resource.get(&service_version_key))
163            .or_else(|| read_from_env("SERVICE_VERSION"))
164            .or_else(|| read_from_env("APP_VERSION"))
165            .unwrap_or_else(|| self.fallback_service_version.into());
166
167        let resource = Resource::builder_empty()
168            .with_detectors(&[
169                Box::new(TelemetryResourceDetector),
170                Box::new(env_detector),
171            ])
172            .with_attributes([
173                KeyValue::new(service_name_key, service_name_value),
174                KeyValue::new(service_version_key, service_version_value),
175            ])
176            .build();
177
178        // Debug
179        resource.iter().for_each(
180            |kv| tracing::debug!(target: "otel::setup::resource", key = %kv.0, value = %kv.1),
181        );
182
183        resource
184    }
185}
186
187macro_rules! fmt_layer {
188    () => {{
189        let layer = tracing_subscriber::fmt::layer();
190
191        #[cfg(debug_assertions)]
192        let layer = layer.compact().with_span_events(FmtSpan::CLOSE);
193        #[cfg(not(debug_assertions))]
194        let layer = layer.json().event_format(fmt::JsonFormat);
195
196        layer.with_writer(std::io::stdout)
197    }};
198}
199
200/// Initializes tracing with OpenTelemetry integration and fallback service information.
201///
202/// This function sets up a complete tracing infrastructure including:
203/// - A temporary subscriber for setup logging
204/// - Resource detection from environment variables with fallbacks
205/// - OTLP tracer provider initialization
206/// - Global propagator configuration
207/// - Final subscriber with both console output and OpenTelemetry export
208///
209/// # Arguments
210///
211/// - `log_level`: The minimum log level for events
212/// - `fallback_service_name`: Default service name if not found in environment variables
213/// - `fallback_service_version`: Default service version if not found in environment variables
214///
215/// # Returns
216///
217/// A configured [`TracerProvider`] that should be kept alive for the duration of the application
218/// and passed to [`shutdown_tracer_provider`] on shutdown.
219///
220/// # Examples
221///
222/// ```rust
223/// use telemetry_rust::{init_tracing_with_fallbacks, shutdown_tracer_provider};
224/// use tracing::Level;
225///
226/// let tracer_provider = init_tracing_with_fallbacks(Level::INFO, "my-service", "1.0.0");
227///
228/// // Your application code here...
229///
230/// shutdown_tracer_provider(&tracer_provider);
231/// ```
232///
233/// # Panics
234///
235/// This function will panic if:
236/// - The OTLP tracer provider cannot be initialized
237/// - The text map propagator cannot be configured
238pub fn init_tracing_with_fallbacks(
239    log_level: tracing::Level,
240    fallback_service_name: &'static str,
241    fallback_service_version: &'static str,
242) -> TracerProvider {
243    // set to debug to log detected resources, configuration read and infered
244    let setup_subscriber = tracing_subscriber::registry()
245        .with(Into::<LevelFilter>::into(log_level))
246        .with(fmt_layer!());
247    let _guard = tracing::subscriber::set_default(setup_subscriber);
248    tracing::info!("init logging & tracing");
249
250    let otel_rsrc =
251        DetectResource::new(fallback_service_name, fallback_service_version).build();
252    let tracer_provider =
253        otlp::init_tracer(otel_rsrc, otlp::identity).expect("TracerProvider setup");
254
255    global::set_tracer_provider(tracer_provider.clone());
256    global::set_text_map_propagator(
257        propagation::TextMapSplitPropagator::from_env().expect("TextMapPropagator setup"),
258    );
259
260    let otel_layer =
261        OpenTelemetryLayer::new(tracer_provider.tracer(env!("CARGO_PKG_NAME")));
262    let subscriber = tracing_subscriber::registry()
263        .with(Into::<filter::TracingFilter>::into(log_level))
264        .with(fmt_layer!())
265        .with(otel_layer);
266    tracing::subscriber::set_global_default(subscriber).unwrap();
267
268    tracer_provider
269}
270
271/// Convenience macro for initializing tracing with package name and version as fallbacks.
272///
273/// This macro calls [`init_tracing_with_fallbacks`] using the current package's name and version
274/// from `CARGO_PKG_NAME` and `CARGO_PKG_VERSION` environment variables as fallback values.
275///
276/// # Arguments
277///
278/// - `log_level`: The minimum log level for events (e.g., `Level::INFO`)
279///
280/// # Returns
281///
282/// A configured [`TracerProvider`] that should be kept alive for the duration of the application.
283///
284/// # Examples
285///
286/// ```rust
287/// use telemetry_rust::{init_tracing, shutdown_tracer_provider};
288/// use tracing::Level;
289///
290/// let tracer_provider = init_tracing!(Level::INFO);
291///
292/// // Your application code here...
293///
294/// shutdown_tracer_provider(&tracer_provider);
295/// ```
296#[macro_export]
297macro_rules! init_tracing {
298    ($log_level:expr) => {
299        $crate::init_tracing_with_fallbacks(
300            $log_level,
301            env!("CARGO_PKG_NAME"),
302            env!("CARGO_PKG_VERSION"),
303        )
304    };
305}
306
307/// Properly shuts down a tracer provider, flushing pending spans and cleaning up resources.
308///
309/// This function performs a graceful shutdown of the tracer provider by:
310/// 1. Attempting to flush any pending spans to the exporter
311/// 2. Shutting down the tracer provider and its associated resources
312/// 3. Logging any errors that occur during the shutdown process
313///
314/// # Arguments
315///
316/// - `provider`: Reference to the [`TracerProvider`] to shut down
317///
318/// # Examples
319///
320/// ```rust
321/// use telemetry_rust::{init_tracing, shutdown_tracer_provider};
322/// use tracing::Level;
323///
324/// let tracer_provider = init_tracing!(Level::INFO);
325///
326/// // Your application code here...
327///
328/// shutdown_tracer_provider(&tracer_provider);
329/// ```
330#[inline]
331pub fn shutdown_tracer_provider(provider: &TracerProvider) {
332    if let Err(err) = provider.force_flush() {
333        tracing::warn!(?err, "failed to flush tracer provider");
334    }
335    if let Err(err) = provider.shutdown() {
336        tracing::warn!(?err, "failed to shutdown tracer provider");
337    } else {
338        tracing::info!("tracer provider is shutdown")
339    }
340}