commonware_runtime/tokio/
tracing.rs

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