Installation

Wire the official Rust OpenTelemetry crates to export traces and logs over OTLP, and configure them with environment variables to send telemetry to Sophonz.

This wires up the upstream opentelemetry / opentelemetry-otlp crates — not a Sophonz package. There's no auto-instrumentation agent for Rust, so this is a short setup function you write once; the OTLP exporters it builds already read OTEL_EXPORTER_OTLP_* environment variables when you don't set them programmatically.

Quick start

Enter the collector URL, project, app name, version and app key below to generate the initialization code from those values. Advanced options are behind the "Advanced options" toggle.

// otel.rs — call init_telemetry() once at startup, before serving traffic
use opentelemetry::global;
use opentelemetry::trace::TracerProvider as _;
use opentelemetry::KeyValue;
use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge;
use opentelemetry_otlp::{LogExporter, SpanExporter, WithExportConfig, WithHttpConfig};
use opentelemetry_sdk::logs::SdkLoggerProvider;
use opentelemetry_sdk::trace::SdkTracerProvider;
use opentelemetry_sdk::Resource;
use std::collections::HashMap;
use tracing_subscriber::prelude::*;

fn init_telemetry() -> (SdkTracerProvider, SdkLoggerProvider) {
    let headers = HashMap::from([("authorization".to_string(), "sk_tYtJUa4WweXXedj6lxjSqoPW5O0DnbXz".to_string())]);

    let resource = Resource::builder()
        .with_service_name("next-sample")
        .with_attribute(KeyValue::new("service.version", "1.0.0"))
        .with_attribute(KeyValue::new("service.namespace", "sophonz"))
        .with_attribute(KeyValue::new("service.key", "sk_tYtJUa4WweXXedj6lxjSqoPW5O0DnbXz"))
        .build();

    let span_exporter = SpanExporter::builder()
        .with_http()
        .with_endpoint("https://in.sophonz.ai/v1/traces")
        .with_headers(headers.clone())
        .build()
        .expect("failed to build span exporter");

    let tracer_provider = SdkTracerProvider::builder()
        .with_batch_exporter(span_exporter)
        .with_resource(resource.clone())
        .build();
    global::set_tracer_provider(tracer_provider.clone());
    let tracer = tracer_provider.tracer("next-sample");

    let log_exporter = LogExporter::builder()
        .with_http()
        .with_endpoint("https://in.sophonz.ai/v1/logs")
        .with_headers(headers)
        .build()
        .expect("failed to build log exporter");

    let logger_provider = SdkLoggerProvider::builder()
        .with_batch_exporter(log_exporter)
        .with_resource(resource)
        .build();

    let otel_log_layer = OpenTelemetryTracingBridge::new(&logger_provider);
    let otel_trace_layer = tracing_opentelemetry::layer().with_tracer(tracer);

    tracing_subscriber::registry()
        .with(otel_trace_layer)
        .with(otel_log_layer)
        .init();

    (tracer_provider, logger_provider)
}

fn main() {
    let (tracer_provider, logger_provider) = init_telemetry();

    tracing::info!("service starting");
    // ... run your server ...

    let _ = tracer_provider.shutdown();
    let _ = logger_provider.shutdown();
}

// These can also come from the environment instead of being passed
// programmatically above:
//   OTEL_SERVICE_NAME            service.name (appName)
//   OTEL_EXPORTER_OTLP_ENDPOINT  collector base URL (collectorUrl)
//   OTEL_EXPORTER_OTLP_HEADERS   authorization=<appKey>
//   OTEL_RESOURCE_ATTRIBUTES     service.key=<appKey>,service.namespace=<project>

Prerequisites

  • A recent stable Rust toolchain (edition 2021 or later).
  • A service registered in the Sophonz console, and the sk_... API key issued for it.

Add the dependencies

# Cargo.toml
[dependencies]
opentelemetry = "0.33"
opentelemetry_sdk = { version = "0.33", features = ["rt-tokio"] }
opentelemetry-otlp = { version = "0.33", features = ["http-proto", "reqwest-blocking-client", "reqwest-rustls", "logs", "trace"] }
opentelemetry-appender-tracing = "0.33"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["registry", "env-filter"] }
tracing-opentelemetry = "0.34"

reqwest-rustls gives the exporter a TLS backend. Without it the HTTP client is built with no TLS support and every export to https://in.sophonz.ai fails with a network error.

CAUTION — Match opentelemetry and tracing-opentelemetry versions carefully

tracing-opentelemetry's own version number doesn't mirror opentelemetry's — check its changelog for the release that depends on the opentelemetry version you're using. At the time of writing, opentelemetry 0.33 pairs with tracing-opentelemetry 0.34, not 0.33. A mismatch fails at compile time with a trait-not-satisfied error, so cargo build will tell you immediately if the pair is wrong.

TIP — Get your API key

Log in to the Sophonz console, register the service, and copy the issued sk_... key. It carries your tenant identity — see service.key below.

Set up the SDK

Call this once at startup, before you start serving traffic:

use opentelemetry::global;
use opentelemetry::propagation::TextMapCompositePropagator;
use opentelemetry::trace::TracerProvider as _;
use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge;
use opentelemetry_otlp::{LogExporter, SpanExporter};
use opentelemetry_sdk::logs::SdkLoggerProvider;
use opentelemetry_sdk::propagation::{BaggagePropagator, TraceContextPropagator};
use opentelemetry_sdk::trace::SdkTracerProvider;
use opentelemetry_sdk::Resource;
use tracing_subscriber::prelude::*;
 
fn init_telemetry() -> (SdkTracerProvider, SdkLoggerProvider) {
    let resource = Resource::builder()
        .with_service_name(
            std::env::var("OTEL_SERVICE_NAME").unwrap_or_else(|_| "my-rust-service".into()),
        )
        .build();
 
    // Reads OTEL_EXPORTER_OTLP_ENDPOINT / _PROTOCOL / _HEADERS automatically.
    let span_exporter = SpanExporter::builder()
        .with_http()
        .build()
        .expect("failed to build span exporter");
 
    let tracer_provider = SdkTracerProvider::builder()
        .with_batch_exporter(span_exporter)
        .with_resource(resource.clone())
        .build();
    global::set_tracer_provider(tracer_provider.clone());
    // Not set by default: without it, traceparent is neither read nor sent.
    global::set_text_map_propagator(TextMapCompositePropagator::new(vec![
        Box::new(TraceContextPropagator::new()),
        Box::new(BaggagePropagator::new()),
    ]));
    let tracer = tracer_provider.tracer("my-rust-service");
 
    let log_exporter = LogExporter::builder()
        .with_http()
        .build()
        .expect("failed to build log exporter");
 
    let logger_provider = SdkLoggerProvider::builder()
        .with_batch_exporter(log_exporter)
        .with_resource(resource)
        .build();
 
    let otel_log_layer = OpenTelemetryTracingBridge::new(&logger_provider);
    let otel_trace_layer = tracing_opentelemetry::layer().with_tracer(tracer);
 
    tracing_subscriber::registry()
        .with(otel_trace_layer)
        .with(otel_log_layer)
        .init();
 
    (tracer_provider, logger_provider)
}
 
fn main() {
    let (tracer_provider, logger_provider) = init_telemetry();
 
    tracing::info!("service starting");
    // ... run your server ...
 
    let _ = tracer_provider.shutdown();
    let _ = logger_provider.shutdown();
}

tracing_subscriber::registry() becomes your global tracing subscriber, so any tracing::info!, tracing::error!, or #[tracing::instrument] call anywhere in your app — and in instrumented dependencies — now produces OTel spans and log records. The propagator call makes the W3C traceparent and baggage headers usable by the framework middleware; the Rust crates do not read OTEL_PROPAGATORS. Call shutdown() on both providers before the process exits so the batch exporters flush.

Configure environment variables

OTEL_SERVICE_NAME=my-rust-service
OTEL_EXPORTER_OTLP_ENDPOINT=https://in.sophonz.ai
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
OTEL_EXPORTER_OTLP_HEADERS=authorization=sk_your_api_key
OTEL_RESOURCE_ATTRIBUTES=service.key=sk_your_api_key,service.namespace=my-project,deployment.environment.name=production
VariableValueNotes
OTEL_SERVICE_NAMEyour service nameRead in the setup snippet above via std::env::var. Must match the service name registered in the console — the portal joins telemetry to the registered service on (project, service.name).
OTEL_EXPORTER_OTLP_ENDPOINThttps://in.sophonz.aiBase OTLP endpoint. SpanExporter/LogExporter with .with_http() derive /v1/traces and /v1/logs from it.
OTEL_EXPORTER_OTLP_PROTOCOLhttp/protobufRead automatically by the .with_http() builder.
OTEL_EXPORTER_OTLP_HEADERSauthorization=sk_your_api_keySent as an HTTP header on every export request.
OTEL_RESOURCE_ATTRIBUTESservice.key=sk_your_api_key,service.namespace=...,deployment.environment.name=...service.key is the tenant identity the collector checks — required. service.namespace groups services into a project; deployment.environment.name labels the environment. Add these with Resource::builder().with_attributes(...) if you'd rather not depend on the env var being read automatically for resource attributes.

CAUTION — service.key is required

The collector runs in enforce mode: telemetry without a resolvable service.key resource attribute is dropped silently. Your process keeps running, .build() doesn't error, and nothing shows up in Sophonz. Always include service.key in OTEL_RESOURCE_ATTRIBUTES, and send the same key as the authorization header via OTEL_EXPORTER_OTLP_HEADERS.

Framework notes

The setup above is framework-agnostic. It hooks into tracing, and a middleware crate creates one tracing span per request:

FrameworkMiddleware
Axum, any tower servicetower-http's TraceLayer, or axum-tracing-opentelemetry
Actix Webtracing-actix-web with its opentelemetry_0_33 feature
tonictonic-tracing-opentelemetry

Versions, complete examples, and how each one continues an incoming trace are in Framework Middleware.

Verify

Run your service with the environment variables set:

OTEL_SERVICE_NAME=my-rust-service \
OTEL_EXPORTER_OTLP_ENDPOINT=https://in.sophonz.ai \
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf \
OTEL_EXPORTER_OTLP_HEADERS=authorization=sk_your_api_key \
OTEL_RESOURCE_ATTRIBUTES=service.key=sk_your_api_key,service.namespace=my-project,deployment.environment.name=production \
cargo run

Export failures are handled by the batch processor's internal error channel, not surfaced as a panic or returned error — so a clean run doesn't guarantee telemetry arrived. An invalid or missing service.key fails exactly the same way as a working setup, just with nothing to show for it. Generate some traffic, then check the Sophonz console for the service you registered.

The sophonz crate

If you would rather not write the setup function, the sophonz crate does the same wiring in one call: the exporters, the resource attributes, the authorization header and a panic hook that sends the panic as an error log before the process exits. It is built on the same opentelemetry 0.33 crates, so everything on the following pages — middleware, propagation, database spans — works unchanged on top of it.

Cargo.toml
[dependencies]
sophonz = { git = "https://github.com/sophonz-labs/sophonz-rust-sdk", tag = "v0.1.1" }
src/main.rs
use sophonz::{Config, Platform};
 
let mut config = Config::new("<service key>", "my-service", Platform::Server);
config.service_version = Some(env!("CARGO_PKG_VERSION").into());
let sophonz = sophonz::init(config)?;
 
// ... run the server ...
 
sophonz.shutdown(); // flushes pending spans and logs

init registers the global tracer provider. It does not install a propagator or a logger: call set_text_map_propagator as shown above, and forward your logs to sophonz.log_bridge().

The repository is private and the crate is not on crates.io. Cargo needs read access to it: set CARGO_NET_GIT_FETCH_WITH_CLI=true and use a git that is authenticated to GitHub. The crate does not include HTTP middleware; use the framework layers in Frameworks.

Next steps

TIP — This is just the beginning

Now ship your app. Sophonz surfaces the problems real users hit — so your app evolves on its own.