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