Skip to main content

commonware_runtime/tokio/
tracing.rs

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