OpenTelemetry
Rust
Quick Start

Rust (OpenTelemetry)

Let a coding agent do this setup
1Install the Traceway skills
2Run it in Claude Code

It adds OpenTelemetry to your Rust service and checks that data arrives. How the setup skill works

Instrument a Rust service with the OpenTelemetry Rust SDK and export traces, logs and metrics to Traceway over OTLP/HTTP.

The example is an axum service on tokio. The request spans come from the opentelemetry-instrumentation-tower layer, logs go through the tracing crate, and spans and metrics use the OpenTelemetry API directly. Rust has no agent, so the setup is one module that builds the three pipelines.

Requirements

  • Rust 1.81 or newer.
  • A Traceway project created with framework OpenTelemetry, and that project's token.

Install

Cargo.toml
[package]
name = "my-rust-service"
version = "1.0.0"
edition = "2021"
 
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "signal"] }
tower-http = { version = "0.7", features = ["catch-panic"] }
serde_json = "1"
 
opentelemetry = "0.33"
opentelemetry_sdk = "0.33"
opentelemetry-otlp = { version = "0.33", default-features = false, features = [
    "http-proto",
    "reqwest-blocking-client",
    "reqwest-rustls",
    "trace",
    "metrics",
    "logs",
    "internal-logs",
] }
opentelemetry-appender-tracing = "0.33"
opentelemetry-instrumentation-tower = { version = "0.19", features = ["axum"] }
 
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }

Three of those feature flags decide whether anything arrives:

  • reqwest-blocking-client, not reqwest-client. The SDK exports from its own threads, outside the tokio runtime. With the async client those threads panic with there is no reactor running and nothing is exported. The blocking client works inside #[tokio::main] as well.
  • reqwest-rustls gives the exporter TLS. Without it, an https:// endpoint fails with network error and no connection is made.
  • axum on opentelemetry-instrumentation-tower. It is off by default, and without it every request span is named GET with no route.

http-proto with default-features = false keeps gRPC and its dependencies out of the build. This guide was checked with the 0.33.1 releases of the OpenTelemetry crates and opentelemetry-instrumentation-tower 0.19.0.

Configure

The exporters and the default resource read these from the process environment.

export OTEL_SERVICE_NAME=my-rust-service
export OTEL_RESOURCE_ATTRIBUTES="service.version=1.0.0"
export OTEL_EXPORTER_OTLP_ENDPOINT=https://cloud.tracewayapp.com/api/otel
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-project-token"
export OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=delta
  • OTEL_EXPORTER_OTLP_ENDPOINT takes the base URL. The exporters append /v1/traces, /v1/metrics and /v1/logs themselves.
  • OTEL_SERVICE_NAME becomes the Server Name on every endpoint, task and issue. Version travels in OTEL_RESOURCE_ATTRIBUTES. There is no OTEL_SERVICE_VERSION variable.
  • The temporality line makes counters and histograms send what changed since the last export, not the running total.
  • With the features above the exporters speak OTLP/HTTP with protobuf, which is what Traceway accepts, so OTEL_EXPORTER_OTLP_PROTOCOL is not needed.

Start the SDK

src/telemetry.rs
use std::backtrace::Backtrace;
 
use opentelemetry::trace::{Status, TraceContextExt};
use opentelemetry::{global, Context, KeyValue};
use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge;
use opentelemetry_otlp::{LogExporter, MetricExporter, SpanExporter};
use opentelemetry_sdk::logs::SdkLoggerProvider;
use opentelemetry_sdk::metrics::SdkMeterProvider;
use opentelemetry_sdk::propagation::TraceContextPropagator;
use opentelemetry_sdk::trace::SdkTracerProvider;
use tracing_subscriber::prelude::*;
use tracing_subscriber::EnvFilter;
 
pub struct Telemetry {
    tracer_provider: SdkTracerProvider,
    meter_provider: SdkMeterProvider,
    logger_provider: SdkLoggerProvider,
}
 
pub fn init() -> Result<Telemetry, Box<dyn std::error::Error + Send + Sync>> {
    let meter_provider = SdkMeterProvider::builder()
        .with_periodic_exporter(MetricExporter::builder().with_http().build()?)
        .build();
    global::set_meter_provider(meter_provider.clone());
 
    let logger_provider = SdkLoggerProvider::builder()
        .with_batch_exporter(LogExporter::builder().with_http().build()?)
        .build();
 
    let otel_layer = OpenTelemetryTracingBridge::new(&logger_provider).with_filter(
        EnvFilter::new("info")
            .add_directive("hyper=off".parse()?)
            .add_directive("reqwest=off".parse()?),
    );
    let stdout_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
    let stdout_layer = tracing_subscriber::fmt::layer().with_filter(stdout_filter);
    tracing_subscriber::registry()
        .with(otel_layer)
        .with(stdout_layer)
        .init();
 
    let tracer_provider = SdkTracerProvider::builder()
        .with_batch_exporter(SpanExporter::builder().with_http().build()?)
        .build();
    global::set_tracer_provider(tracer_provider.clone());
 
    global::set_text_map_propagator(TraceContextPropagator::new());
 
    record_panics_on_the_active_span();
 
    Ok(Telemetry {
        tracer_provider,
        meter_provider,
        logger_provider,
    })
}
 
impl Telemetry {
    pub fn shutdown(self) {
        for (signal, result) in [
            ("traces", self.tracer_provider.shutdown()),
            ("logs", self.logger_provider.shutdown()),
            ("metrics", self.meter_provider.shutdown()),
        ] {
            if let Err(error) = result {
                eprintln!("failed to shut down {signal}: {error}");
            }
        }
    }
}
 
pub fn record_exception(exception_type: &str, message: &str, stacktrace: &Backtrace) {
    let cx = Context::current();
    let span = cx.span();
    span.add_event(
        "exception",
        vec![
            KeyValue::new("exception.type", exception_type.to_owned()),
            KeyValue::new("exception.message", message.to_owned()),
            KeyValue::new("exception.stacktrace", stacktrace.to_string()),
        ],
    );
    span.set_status(Status::error(message.to_owned()));
}
 
fn record_panics_on_the_active_span() {
    let default_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        let message = info.payload_as_str().unwrap_or("panic");
        record_exception("panic", message, &Backtrace::force_capture());
        default_hook(info);
    }));
}

What this module does that is easy to miss:

  • The propagator. Without set_text_map_propagator, an incoming traceparent header is ignored and traces across services never link. OTEL_PROPAGATORS is not read.
  • The log bridge filter. The HTTP client the exporter uses logs through tracing too. hyper=off and reqwest=off keep the bridge from exporting log lines about its own exports.
  • The stdout layer. It is the only place the SDK reports a failed export. A wrong token shows as status code: 401. Run with RUST_LOG=info,opentelemetry=debug to see the reason behind a network error.
  • shutdown. Call it before the process exits. Without it the last spans, the metrics and the last log lines are lost.

Instrument the Server

src/main.rs
mod error;
mod telemetry;
 
use std::sync::LazyLock;
 
use axum::extract::Path;
use axum::routing::get;
use axum::{Json, Router};
use error::AppError;
use opentelemetry::metrics::Counter;
use opentelemetry::trace::{SpanKind, TraceContextExt, Tracer};
use opentelemetry::{global, Context, KeyValue};
use opentelemetry_instrumentation_tower::http::server::LayerBuilder;
use serde_json::{json, Value};
use tower_http::catch_panic::CatchPanicLayer;
 
const SCOPE: &str = "my-rust-service";
 
static SESSIONS_CLEANED: LazyLock<Counter<u64>> =
    LazyLock::new(|| global::meter(SCOPE).u64_counter("app.sessions_cleaned").build());
 
async fn get_user(Path(id): Path<u64>) -> Json<Value> {
    tracing::info!("looking up user {id}");
    let user = global::tracer(SCOPE).in_span("load-user", |_cx| {
        json!({ "id": id, "name": format!("user-{id}") })
    });
    Json(user)
}
 
async fn boom() -> &'static str {
    panic!("boom: something went wrong")
}
 
async fn fail() -> Result<String, AppError> {
    let limit: u32 = "not a number".parse()?;
    Ok(format!("limit is {limit}\n"))
}
 
async fn run_job() -> &'static str {
    let tracer = global::tracer(SCOPE);
    let span = tracer
        .span_builder("cleanup-expired-sessions")
        .with_kind(SpanKind::Consumer)
        .start_with_context(&tracer, &Context::new());
    let _active = Context::new().with_span(span).attach();
 
    SESSIONS_CLEANED.add(7, &[KeyValue::new("job", "cleanup-expired-sessions")]);
    "cleaned 7 sessions\n"
}
 
async fn shutdown_signal() {
    let mut terminate =
        tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).unwrap();
    tokio::select! {
        _ = tokio::signal::ctrl_c() => {}
        _ = terminate.recv() => {}
    }
}
 
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let telemetry = telemetry::init()?;
 
    let app = Router::new()
        .route("/users/{id}", get(get_user))
        .route("/boom", get(boom))
        .route("/fail", get(fail))
        .route("/run-job", get(run_job))
        .layer(CatchPanicLayer::new())
        .layer(LayerBuilder::builder().with_metrics(false).build()?);
 
    let port = std::env::var("PORT").unwrap_or_else(|_| "8080".into());
    let listener = tokio::net::TcpListener::bind(format!("127.0.0.1:{port}")).await?;
    tracing::info!("listening on {}", listener.local_addr()?);
    axum::serve(listener, app)
        .with_graceful_shutdown(shutdown_signal())
        .await?;
 
    telemetry.shutdown();
    Ok(())
}
src/error.rs
use std::backtrace::Backtrace;
 
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
 
use crate::telemetry;
 
pub struct AppError {
    error_type: &'static str,
    message: String,
    backtrace: Backtrace,
}
 
impl<E: std::error::Error> From<E> for AppError {
    fn from(error: E) -> Self {
        Self {
            error_type: std::any::type_name::<E>(),
            message: error.to_string(),
            backtrace: Backtrace::force_capture(),
        }
    }
}
 
impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        telemetry::record_exception(self.error_type, &self.message, &self.backtrace);
        StatusCode::INTERNAL_SERVER_ERROR.into_response()
    }
}

Run it with the variables from Configure set:

PORT=8080 cargo run

Endpoints

LayerBuilder::builder().build() creates a SERVER span for every request, sets http.route from the route axum matched, and marks the span as failed on a 5xx. .route("/users/{id}", ...) becomes the endpoint GET /users/{id}.

The order of the two layers matters. The last .layer(...) call is the outermost, and the OpenTelemetry layer has to wrap CatchPanicLayer so it sees the 500 that layer makes out of a panic.

with_metrics(false) leaves out the http.server.* histograms the layer would otherwise record, one series per route, method and status. Traceway already computes request counts and latency from spans.

Exceptions

Nothing in the Rust instrumentation records exceptions by itself. The layer marks a 5xx span as failed, but Traceway builds an Issue from an exception event on the span, and that event is yours to add. record_exception in telemetry.rs writes it, and two paths call it:

  • A handler returns an error. AppError in error.rs is the handlers' error type. The ? operator converts any error into it and captures the type name and a backtrace at that point. into_response records the event and answers 500. This is the path almost every failure in a Rust service takes.
  • A handler panics. CatchPanicLayer turns the panic into a 500 instead of a dropped connection, and the panic hook installed by record_panics_on_the_active_span records the event.

Stack traces come from std::backtrace::Backtrace. A build without debug information gives function names only.

Logs

OpenTelemetryTracingBridge turns tracing events into log records. A line written inside a request carries that request's trace id:

tracing::info!("looking up user {id}");

The SDK logs through tracing as well, so lines such as Global tracer provider is set appear in Logs. Add .add_directive("opentelemetry=off".parse()?) to the bridge filter to leave them out.

Background Tasks

A job appears under Tasks when its span has kind Consumer. A root span with the default kind is dropped.

let tracer = global::tracer("my-rust-service");
let span = tracer
    .span_builder("cleanup-expired-sessions")
    .with_kind(SpanKind::Consumer)
    .start_with_context(&tracer, &Context::new());
let _active = Context::new().with_span(span).attach();

The span name is the task name, so keep it stable and put job ids and batch sizes in attributes. Starting from Context::new() makes the job the root of its own trace. It matters when the job is started from inside a request, as in this example.

Custom Metrics

static SESSIONS_CLEANED: LazyLock<Counter<u64>> =
    LazyLock::new(|| global::meter("my-rust-service").u64_counter("app.sessions_cleaned").build());
 
SESSIONS_CLEANED.add(7, &[KeyValue::new("job", "cleanup-expired-sessions")]);

The counter appears in metric discovery as app.sessions_cleaned, with job as a tag you can group by. Metrics export every 60 seconds by default. While you are checking the integration, set OTEL_METRIC_EXPORT_INTERVAL=5000, and remove it afterwards.

Verify It Worked

Start the service, then send a few requests:

curl localhost:8080/users/101
curl localhost:8080/users/102
curl localhost:8080/users/103
curl localhost:8080/boom
curl localhost:8080/fail
curl localhost:8080/run-job

Set the dashboard time picker to the last 15 minutes and check:

  1. Endpoints. One row GET /users/{id} with a count of 3, and GET /boom and GET /fail with status 500. Rows named UNMATCHED for your own routes mean the axum feature is missing.
  2. Issues. Two of them, one for the panic and one for the parse error from /fail, each with a stack trace.
  3. Logs. Three looking up user lines, each linked to its trace.
  4. Tasks. cleanup-expired-sessions.
  5. Metrics. app.sessions_cleaned in metric discovery, and no http.server.* names.

Nothing at all? Read the service's own output: export failures are printed there.

Next Steps

  • Traces: how OTel spans map to Endpoints, Tasks and Issues
  • Logs: log record mapping and severity handling
  • Metrics: supported metric types and histogram handling
  • Overview: protocol details, authentication, and a "nothing is showing up" checklist