Skip to content

Lesson 9 of 14 · 18m

Tracing and Observability for Services

Spans over log lines, #[instrument] and Instrument across tokio::spawn, JSON subscribers with EnvFilter, and keeping secrets out of span fields.

The service logs plenty — println!("got request"), eprintln!("db slow: {}ms", elapsed), a log::info! here and there. Then production gets its first real incident and the log is a million-line smear: you can see a request failed, but not which one, and the eight interleaved requests on the same worker thread all look identical. log gives you events. tracing gives you spans — the request's whole causal tree, attached to every event inside it. That's the difference between a log file and a trace.

Events vs spans — the model that matters

log::info!("user created") is an event: a point in time, no parents, no context beyond the message. tracing adds spans — named, structured regions that events happen inside:

use tracing::{info, instrument, Instrument};

#[instrument(name = "create_user", skip(store), fields(user_id = %id))]
async fn create_user(id: UserId, store: &impl UserStore) -> Result<User, UserError> {
    info!("validating");                        // logged INSIDE create_user span
    let user = store.insert(&new_user(id)).await?;
    info!(username = %user.name, "created");    // fields, not format strings
    Ok(user)
}

#[instrument] wraps the function in a span named for the function with the fields you declare. Every info!/debug! inside it — on this task, or any task it spawns with the span attached — carries that span's fields. The request-id problem every service eventually hand-rolls is this, for free: #[instrument(fields(request_id = %uuid))] on the outermost handler and every event down the tree inherits it.

The trap: spans don't follow tokio::spawn automatically — the spawned task has its own context. task.instrument(parent_span) or .in_current_span() is the bridge; forget it and your trace splits into two disconnected stories at exactly the concurrency boundary you were tracing.

Structured output: fields beat format strings

The wrong mental model is "the message is the log." info!("user {} failed with {}", id, err) produces a string you can only grep. info!(user_id = %id, error = %err, "creation failed") produces fields — filterable, indexable, searchable in any structured sink. tracing_subscriber::fmt().json() turns spans into JSON logs Loki/Elastic/anything ingests:

tracing_subscriber::fmt()
    .json()
    .with_env_filter(EnvFilter::from_default_env()) // RUST_LOG=create_user=debug
    .init();

EnvFilter reads RUST_LOG — RUST_LOG=my_crate=info,my_crate::repo=debug is per-module verbosity in production without a redeploy. That's the part println! can never give you: a dial, not a firehose.

Spans are the context — and tower-http already made them

If you're on Axum, tower_http::trace::TraceLayer creates a span per request with method/path/latency fields already attached. Your #[instrument]'d handler nests inside it. The request's trace is a tree: http_request → create_user → insert. That tree is what a "distributed trace" is when you eventually ship spans to OpenTelemetry — tracing-opentelemetry bridges to OTLP, so the same #[instrument] annotations become Jaeger/Tempo spans with zero code change.

tokio-console is the other half nobody mentions: console_subscriber::init() plus --cfg tokio_unstable gives you a live view of every task the runtime is polling — how long each task is scheduled, where it's parked, which Mutex/Semaphore it's blocked on. It's htop for your async runtime, and it's how you see the blocking-wall from the async lesson instead of inferring it from latency.

Fields, not secrets

#[instrument] records arguments by default — which means #[instrument] on fn login(password: &str) writes the password to every span in the trace. skip(password) is the fix, and skip_all plus named fields() is the habit:

#[instrument(skip(password), fields(username = %username))]
async fn login(username: &str, password: &str) -> Result<Session, AuthError> { /* ... */ }

The rule is the same one as error responses: what reaches the observability pipeline is a security boundary — fields are data, and data you exfiltrate to a log aggregator is data you have to treat as exfiltrated.

The bug that ships

The observability bug that ships is log::info! on a hot path with RUST_LOG=debug baked into the Dockerfile — the service works, then someone notices the p99 is logging overhead and the fix is a config line nobody wrote. Set the default filter level deliberately (info in prod, debug in dev), keep the JSON formatter off until the pipeline needs it, and let EnvFilter be a deploy-time decision.

Try this

Instrument one handler with #[instrument(fields(request_id))], call a tokio::spawn'd helper with and without .instrument(span), and grep the output for the request_id — count how many events the trace "loses" at the spawn boundary. Then add console-subscriber and watch a spawn_blocking call actually show up as parked time.

Field notes

  • tracing and log interop through tracing-log — a log-only dependency still reaches your subscriber.
  • Instrument is for Futures; for a spawned JoinHandle, wrap the future before spawn, not the handle.
  • The metrics crate pairs with tracing for counters/histograms — spans are causality, metrics are cardinality.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.