OpenTelemetry Rust distro for Uptrace

Uptrace is an open-source, OpenTelemetry-native APM platform. This document explains how to configure the OpenTelemetry Rust SDK to export spans (traces), logs, and metrics to Uptrace using OTLP.

Choose Your Setup Path

Option A: Quick Start with the uptrace crate

Best for: Getting started quickly, automatic configuration

uptrace is a thin wrapper over opentelemetry-rust that configures the OpenTelemetry SDK to export traces, metrics, and logs to Uptrace. It does not add any new functionality and is provided only for your convenience.

Continue below

Option B: Direct OTLP Configuration

Best for: Existing OpenTelemetry users, custom exporters, fine-grained control

Direct OTLP Setup

Quick Start Guide

Follow these steps to get your first trace running in 5 minutes:

Step 1: Create an Uptrace Project

Create an Uptrace project (or self-host Uptrace) to obtain a DSN (Data Source Name), for example, https://<secret>@api.uptrace.dev?grpc=4317.

Step 2: Install the uptrace crate

shell
cargo add uptrace opentelemetry

Or add the dependencies to your Cargo.toml manually:

toml
[dependencies]
uptrace = "0.33"
opentelemetry = "0.33"

The uptrace crate version follows the OpenTelemetry Rust version it is built with. Keep opentelemetry on the same version, or use the re-exported uptrace::opentelemetry and uptrace::opentelemetry_sdk crates.

Step 3: Basic Configuration

You can configure the Uptrace client using a DSN (Data Source Name) from the project settings page. Replace myservice with a name that identifies your application.

rust
let uptrace = uptrace::Uptrace::builder()
    // copy your project DSN here or use UPTRACE_DSN env var
    //.with_dsn("<FIXME>")
    .with_service_name("myservice")
    .with_service_version("1.0.0")
    .with_deployment_environment("production")
    .build()?;

build() creates and registers the global tracer and meter providers, so you can use opentelemetry::global anywhere in your code. Call uptrace.shutdown() before the program exits to send buffered data.

Step 4: Create Your First Trace

Copy the code to src/main.rs:

rust
use std::thread;
use std::time::Duration;

use opentelemetry::trace::{TraceContextExt, Tracer};
use opentelemetry::{global, KeyValue};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Configure OpenTelemetry with sensible defaults.
    let uptrace = uptrace::Uptrace::builder()
        // copy your project DSN here or use UPTRACE_DSN env var
        //.with_dsn("<FIXME>")
        .with_service_name("myservice")
        .with_service_version("1.0.0")
        .build()?;

    // Create a tracer. Usually, tracer is a global variable.
    let tracer = global::tracer("app_or_crate_name");

    // Create a root span (a trace) to measure some operation.
    tracer.in_span("main-operation", |cx| {
        // Spans created inside the closure become children of main-operation.
        tracer.in_span("GET /posts/:id", |cx| {
            thread::sleep(Duration::from_millis(10));

            let span = cx.span();
            span.set_attribute(KeyValue::new("http.request.method", "GET"));
            span.set_attribute(KeyValue::new("http.route", "/posts/:id"));
            span.set_attribute(KeyValue::new("http.response.status_code", 200));

            // Record an error on the current span.
            uptrace.report_error(&std::io::Error::other("dummy error"));
        });

        tracer.in_span("SELECT", |cx| {
            thread::sleep(Duration::from_millis(20));

            let span = cx.span();
            span.set_attribute(KeyValue::new("db.system.name", "mysql"));
            span.set_attribute(KeyValue::new("db.query.text", "SELECT * FROM posts LIMIT 100"));
        });

        println!("trace: {}", uptrace.trace_url(cx.span().span_context()));
    });

    // Send buffered data and free resources.
    uptrace.shutdown()?;
    Ok(())
}

Step 5: Run Your Application

Run the code, replacing <FIXME> with your Uptrace DSN:

shell
$ UPTRACE_DSN="<FIXME>" cargo run
trace: https://app.uptrace.dev/traces/<trace_id>?span_id=<span_id>

Step 6: View Your Trace

Follow the link to view the trace:

Basic trace

Configuration Options

You can find the full list of available options at docs.rs.

OptionDescription
with_dsnA data source that specifies Uptrace project credentials. For example, https://<secret>@api.uptrace.dev?grpc=4317.
with_service_nameservice.name resource attribute. For example, myservice.
with_service_versionservice.version resource attribute. For example, 1.0.0.
with_deployment_environmentdeployment.environment resource attribute. For example, production.
with_resource_attributesAny other resource attributes.
with_resource_detectorAdds a resource detector, for example, for Kubernetes or containers.
with_resourceResource that replaces all detected and configured attributes.
with_traces, with_metrics, with_logsConfigures each signal, for example, a sampler via TracesConfig::with_sampler.
without_traces, without_metrics, without_logsDisables a signal.
with_protocolProtocol::Http (default) or Protocol::Grpc.
with_propagatorGlobal propagator. Defaults to W3C TraceContext + Baggage.
with_panic_hookRecords panics as span exceptions.

The Uptrace handle returned by build() provides trace_url, current_trace_url, report_error, force_flush, and shutdown.

Cargo features

FeatureDescription
http (default)Exports data using OTLP/HTTP (protobuf). Does not require an async runtime.
grpcExports data using OTLP/gRPC (tonic). Requires a Tokio runtime.
tracingIntegration with the tracing crate (spans and logs).
internal-logs (default)Reports internal diagnostics via tracing.

For example, to export over gRPC only:

toml
[dependencies]
uptrace = { version = "0.33", default-features = false, features = ["grpc"] }

Environment variables

Environment VariableDescription
UPTRACE_DSNUptrace DSN, used when with_dsn is not called
UPTRACE_DISABLEDDisables Uptrace: build() returns a no-op handle
OTEL_SERVICE_NAMEService name (e.g., myservice)
OTEL_RESOURCE_ATTRIBUTESAdditional resource attributes
OTEL_TRACES_SAMPLERSampling strategy (e.g., parentbased_traceidratio)
OTEL_TRACES_SAMPLER_ARGSampling argument (e.g., 0.1 for 10%)

Uptrace fully supports the OpenTelemetry Protocol (OTLP) over both gRPC and HTTP transports.
If you already have an OTLP exporter configured, you can continue using it with Uptrace by simply pointing it to the Uptrace OTLP endpoint.

Connecting to Uptrace

Choose an OTLP endpoint from the table below and pass your DSN via the uptrace-dsn header for authentication:

TransportEndpointPort
gRPChttps://api.uptrace.dev:43174317
HTTPhttps://api.uptrace.dev443

When using HTTP transport, you often need to specify the full URL for each signal type:

  • https://api.uptrace.dev/v1/traces
  • https://api.uptrace.dev/v1/logs
  • https://api.uptrace.dev/v1/metrics

Note: Most OpenTelemetry SDKs support both transports. Use HTTP unless you're already familiar with gRPC.

For performance and reliability, we recommend:

  • Use BatchSpanProcessor and BatchLogProcessor for batching spans and logs, reducing the number of export requests.
  • Enable gzip compression to reduce bandwidth usage.
  • Prefer delta metrics temporality (Uptrace converts cumulative metrics automatically).
  • Use Protobuf encoding instead of JSON (Protobuf is more efficient and widely supported).
  • Use HTTP transport for simplicity and fewer configuration issues (unless you're already familiar with gRPC).
  • Optionally, use the AWS X-Ray ID generator to produce trace IDs compatible with AWS X-Ray.

Common Environment Variables

You can use environment variables to configure resource attributes and propagators::

VariableDescription
OTEL_RESOURCE_ATTRIBUTESComma-separated resource attributes, e.g., service.name=myservice,service.version=1.0.0.
OTEL_SERVICE_NAME=myserviceSets the service.name attribute (overrides OTEL_RESOURCE_ATTRIBUTES).
OTEL_PROPAGATORSComma-separated list of context propagators (default: tracecontext,baggage).

Most language SDKs allow configuring the OTLP exporter entirely via environment variables:

shell
# Endpoint (choose HTTP or gRPC)
export OTEL_EXPORTER_OTLP_ENDPOINT="https://api.uptrace.dev"         # HTTP
#export OTEL_EXPORTER_OTLP_ENDPOINT="https://api.uptrace.dev:4317"   # gRPC

# Pass DSN for authentication
export OTEL_EXPORTER_OTLP_HEADERS="uptrace-dsn=<FIXME>"

# Performance optimizations
export OTEL_EXPORTER_OTLP_COMPRESSION=gzip
export OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION=BASE2_EXPONENTIAL_BUCKET_HISTOGRAM
export OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=DELTA

Configure BatchSpanProcessor to balance throughput and payload size:

shell
export OTEL_BSP_EXPORT_TIMEOUT=10000         # Max export timeout (ms)
export OTEL_BSP_MAX_EXPORT_BATCH_SIZE=10000  # Avoid >32MB payloads
export OTEL_BSP_MAX_QUEUE_SIZE=30000         # Adjust for available memory
export OTEL_BSP_MAX_CONCURRENT_EXPORTS=2     # Parallel exports

Troubleshooting

Common Issues

No data in Uptrace:

  • Verify the DSN is set correctly, either via .with_dsn("...") or the UPTRACE_DSN environment variable. build() returns an error for an empty or invalid DSN.
  • Check that the endpoint is reachable: https://api.uptrace.dev:443 (HTTP) or https://api.uptrace.dev:4317 (gRPC).
  • Make sure you call uptrace.shutdown() before the program exits — without it, buffered spans are dropped.
  • Check that UPTRACE_DISABLED is not set; uptrace.is_enabled() returns false in that case.

Build errors with mismatched types:

  • Errors such as "expected opentelemetry::..., found a different opentelemetry::..." mean two OpenTelemetry versions are in your dependency tree. Use the same 0.33 version for all opentelemetry* crates, or use the re-exported uptrace::opentelemetry. Run cargo tree -d -i opentelemetry to find duplicates.

gRPC exporter panics or doesn't export:

  • The grpc feature uses tonic, which requires a Tokio runtime. Build Uptrace inside #[tokio::main] and call shutdown() from tokio::task::spawn_blocking.

Logs exported in an infinite loop:

  • When using uptrace.log_layer(), filter out the exporter's own logs with EnvFilter directives such as hyper=off, h2=off, tonic=off, and reqwest=off. See Logs.

What's Next?

Instrument more operations to get a detailed picture of your application. Prioritize network calls, database queries, errors, and logs.

By Use Case

I want to...Read this
Configure OTLP exporter directlyOTLP Configuration
Instrument my code with spansTracing API
Collect application metricsMetrics API
Send logs to UptraceLogs integration
Enable distributed tracingContext propagation
Reduce costs in productionSampling strategies
Auto-detect cloud environmentResource detectors

Framework Guides

OpenTelemetry Rust integrates with popular frameworks through the tracing ecosystem:

FrameworkIntegration
AxumBuilt-in tracing support
Actix-webtracing-actix-web crate
WarpBuilt-in tracing support
HyperBuilt-in tracing support
Reqwesttracing-opentelemetry crate
SQLxBuilt-in tracing support
Tokiotokio-tracing features

See the OTLP Configuration page for Axum and Actix-web integration examples.