commonware_runtime/tokio/
tracing.rs

1//! Utilities to export traces to an OTLP endpoint.
2
3use opentelemetry::{global, trace::TracerProvider};
4use opentelemetry_otlp::{ExporterBuildError, SpanExporter, WithExportConfig};
5use opentelemetry_sdk::{
6    trace::{BatchSpanProcessor, Sampler, SdkTracerProvider, Tracer},
7    Resource,
8};
9use std::time::Duration;
10
11/// Timeout for the OTLP HTTP exporter.
12const TIMEOUT: Duration = Duration::from_secs(15);
13
14/// Configuration for exporting traces to an OTLP endpoint.
15pub struct Config {
16    /// The OTLP endpoint to export traces to.
17    pub endpoint: String,
18    /// The service name to use for the traces.
19    pub name: String,
20    /// The sampling rate to use for the traces.
21    pub rate: f64,
22}
23
24/// Export traces to an OTLP endpoint.
25pub fn export(cfg: Config) -> Result<Tracer, ExporterBuildError> {
26    // Create the OTLP HTTP exporter
27    let exporter = SpanExporter::builder()
28        .with_http()
29        .with_endpoint(cfg.endpoint)
30        .with_timeout(TIMEOUT)
31        .build()?;
32
33    // Configure the batch processor
34    let batch_processor = BatchSpanProcessor::builder(exporter).build();
35
36    // Define the resource with service name
37    let resource = Resource::builder_empty()
38        .with_service_name(cfg.name.clone())
39        .build();
40
41    // Build the tracer provider
42    let sampler = Sampler::TraceIdRatioBased(cfg.rate);
43    let tracer_provider = SdkTracerProvider::builder()
44        .with_span_processor(batch_processor)
45        .with_resource(resource)
46        .with_sampler(sampler)
47        .build();
48
49    // Create the tracer and set it globally
50    let tracer = tracer_provider.tracer(cfg.name);
51    global::set_tracer_provider(tracer_provider);
52    Ok(tracer)
53}