dust

Tracing

Introduction

When a page or API endpoint is slow, a trace shows you exactly where the time went. Each request produces a timeline made up of timed spans for every database query, cache lookup, and outgoing HTTP request, making it easy to spot bottlenecks. dust-framework exports traces using OpenTelemetry to any tool that accepts OTLP, such as Sentry or Grafana.

You don't need to instrument your application manually to get started. Requests, console commands, queued jobs, database queries, and everything else listed in What's traced already emit spans, so once you enable the exporter, traces begin flowing immediately.

Exporting traces

To export traces, add dust-framework's opentelemetry feature to dust-framework in your Cargo.toml:

toml
[dependencies]dust-framework = { version = "0.1", features = ["database-postgres", "opentelemetry"] }

Then configure OpenTelemetry's standard environment variables in your .env file. dust-framework starts exporting traces as soon as an endpoint is configured:

ini
OTEL_SERVICE_NAME=storefront
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318

To try tracing locally, you may run Jaeger in Docker. It accepts traces at the endpoint above and serves its UI at http://localhost:16686:

shell
docker run --rm -p 4318:4318 -p 16686:16686 jaegertracing/jaeger

These are the environment variables most applications configure:

Variable What it does
OTEL_EXPORTER_OTLP_ENDPOINT The base URL to send traces to. dust-framework appends /v1/traces.
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT The full URL to send traces to, instead of appending /v1/traces to the base URL.
OTEL_EXPORTER_OTLP_HEADERS, OTEL_EXPORTER_OTLP_TRACES_HEADERS Request headers to include, such as an API key: x-api-key=secret.
OTEL_SERVICE_NAME The service name your tracing tool groups traces under. Defaults to APP_NAME.
OTEL_RESOURCE_ATTRIBUTES Additional service attributes, such as deployment.environment.name=production.
OTEL_SDK_DISABLED Set to true to disable exporting without removing your endpoint configuration.

dust-framework batches and exports spans in the background so incoming requests never wait on your tracing tool. If the collector is unreachable, your application keeps running and logs the error. Before a console command exits or the server shuts down, dust-framework flushes any buffered spans.

Sentry

Sentry accepts traces over OTLP. Find your project's OTLP traces endpoint and public key under Client Keys (DSN) in your project settings, then add them to .env:

ini
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://o123456.ingest.us.sentry.io/api/7891011/integration/otlp/v1/traces
OTEL_EXPORTER_OTLP_TRACES_HEADERS="x-sentry-auth=sentry sentry_key=your-public-key"

To forward errors to Sentry as well, check out the logging guide's section on Sentry.

Sampling

By default, dust-framework exports every trace. On a busy production application, exporting 100% of traces can get expensive, so you may configure a sampler to keep a percentage of them:

ini
OTEL_TRACES_SAMPLER=parentbased_traceidratio
OTEL_TRACES_SAMPLER_ARG=0.1

With these settings, dust-framework keeps 10% of traces that originate in your service. When a request continues an existing trace from another service, dust-framework follows that upstream sampling decision instead so traces are never split in half.

OTEL_TRACES_SAMPLER accepts always_on, always_off, traceidratio, parentbased_always_on (the default), parentbased_always_off, and parentbased_traceidratio.

What's traced

dust-framework names each span and attaches attributes following OpenTelemetry's semantic conventions:

Span Name
Each HTTP request, except the health route The method and route, such as GET /users/{user}, with HTTP in place of a non-standard method such as PURGE
Each console command, except long-running commands The command's name, such as reports:generate
Each attempt of a queued job The job's name
Each scheduled task The task's description
Each tick The tick's name
Each background task started with task::background background
Each advance of a workflow run workflow and the workflow's name, such as workflow users.onboard
Each attempt of a workflow step step and the step's name, such as step charge card
Each attempt of an outgoing HTTP request The HTTP method, such as GET, or HTTP for a non-standard method
Each database query The SQL operation and table, such as SELECT orders, or the operation alone when no table applies
Each database transaction begun, committed, or rolled back BEGIN, COMMIT, or ROLLBACK, and SAVEPOINT or RELEASE for a nested transaction
Each cache operation The operation name, such as cache.get
Each Redis command or pipeline The command name, such as GET, or PIPELINE
Each email rendered and sent mail.render or mail.send
Each SMS sent sms.send

dust-framework marks a span as failed when a request returns a 5xx status, a command exits with an error, a job attempt, scheduled task, tick, background task, workflow run, or workflow step fails, or a database query, cache operation, Redis command, outgoing request, mail send, or SMS send fails.

When your own code fails a span, such as a handler returning dust::Error::msg("the payment gateway timed out"), the span shows your error's message, so your tracing tool tells you why it failed. When the error came from dust-framework, the span shows a short summary instead, because the error's message can quote your users' data. For example, a PostgreSQL error that quotes the value it couldn't cast shows database error 22P02, a rejected outgoing request shows HTTP 404 without the response body, and a Resend rejection shows Resend rejected the email with HTTP 422 without Resend's message, and a value dust-framework couldn't decode or encode as JSON shows JSON error without quoting the value. The summary wins even when your code adds context to dust-framework's error. Every failed span also records error.type, such as 22P02, 404, or timeout, so you can group failures in your tracing tool. Your logs and error reports still receive the full error.

Spans never include bound query parameters, Redis command arguments, phone numbers, or email addresses, subjects, and bodies. dust-framework replaces every literal in a query's SQL with ?, so where email = 'taylor@example.com' is exported as where email = ?. An outgoing request's URL keeps its query string's parameter names but replaces their values with REDACTED.

When the HTTP client retries a request, each attempt is a span of its own, and each retry records http.request.resend_count. A request that gets a 503 and then succeeds shows as one failed span followed by one successful span.

[!WARNING] dust-framework exports a request's path, such as /reset-password/8f2c..., and each cache key as written, and it exports the messages you log inside a span as they are. Don't put secrets in paths, cache keys, or your own log messages.

When OpenTelemetry tracing is enabled, JSON log lines also include the active span's trace_id and span_id so log tools can link directly to the trace.

Your own spans

dust-framework's built-in spans show you which query was slow, but not which part of your own code triggered it. To see your own functions in a trace, wrap them in custom spans using the tracing crate, which your application already depends on. Your span becomes a child of the active request or command span, and any queries or outgoing requests inside it become children of your span.

The #[tracing::instrument] attribute wraps an entire function in a span named after it. For example, this function finds a user's most popular posts for a weekly digest email:

rust
use dust::prelude::*;use crate::models::{Post, User};#[tracing::instrument(skip_all, fields(user.id = user.id))]pub async fn popular_posts(user: &User) -> dust::Result<Vec<Post>> {    let posts = Post::query()        .filter(Post::user_id.eq(user.id) & Post::votes.gt(100))        .order_by(Post::votes.desc())        .limit(5)        .get()        .await?;    Ok(posts)}

By default, #[tracing::instrument] records every function argument as a span attribute. Passing skip_all keeps sensitive fields like the user's email address out of your traces, while fields(user.id = user.id) records only the user's ID.

To wrap a single future in a span instead of an entire function, import tracing::Instrument and call .instrument(...):

rust
use tracing::Instrument;let posts = load_posts(&user)    .instrument(tracing::info_span!("popular_posts", user.id = user.id))    .await?;

dust-framework exports spans at the debug level and above, so trace_span! stays out of exported traces. Any messages you log inside a span at or above your configured log level are attached to that span as events. dust-framework's own log lines are attached with only their IDs, counts, durations, and names, and a line about an error shows the error's summary, as a failed span does. The log mailer's and SMS sender's previews of a message stay in your local log, and so do lines that other libraries log, such as SQLx's statement lines, which quote your SQL with its values.

A background task spawned with task::spawn inherits the active span automatically. A task spawned with tokio::spawn does not, so its queries appear in separate traces.

Traces across services

When one service calls another, dust-framework propagates traces automatically using W3C Trace Context headers. An incoming request carrying a traceparent header continues that upstream trace, and every outgoing HTTP request sends a traceparent header so downstream services can join your trace.

A queued job also continues the trace of the request or command that dispatched it, even when a worker on another server processes the job. Likewise, when the scheduler runs a scheduled console command, dust-framework links the command's span beneath the scheduled task so the entire schedule:run appears in a single trace. Because dust-framework passes the trace context through the TRACEPARENT and TRACESTATE environment variables, external programs run via exec or shell that read those variables join the same trace automatically.

Cost, privacy, and sampling

A trace answers "where did the time go", and a log answers "what happened at this moment". They overlap, but the trace is sampled and the log is not, so use the trace for latency and the log for events you must not lose. A failed payment should log; a query that took 40 ms can live only in the trace.

Traces are large. Every request produces a span tree, and exporting every one of them to a hosted tool costs money and network bandwidth. Start with parentbased_traceidratio at 0.1 in production and raise it while you investigate a problem. The framework batches spans in the background, so an increased rate costs memory and egress rather than request latency.

Spans deliberately leave out values that could be personal data: query parameters, Redis arguments, email addresses, subjects, bodies, and phone numbers. They do include a request's path, each cache key as written, and the messages you log inside a span. Those three are your responsibility. Do not put a token, an email address, or a reset secret in a path or a cache key, and do not log one inside a span.

When a failed span comes from dust-framework, the span shows a summary such as database error 22P02 or HTTP 404, not the full error, because the message can quote user data. Your logs still receive the full error, so investigate there.

Exporting another way

The OTEL_* environment variables configure an OTLP-over-HTTP exporter. If you need a different exporter, such as one from a vendor crate or a stdout exporter for local debugging, build your own OpenTelemetry tracer provider. First, add the OpenTelemetry crates to Cargo.toml using the same version dust-framework uses so your provider's type matches what tracer_provider expects:

toml
opentelemetry_sdk = "0.33"opentelemetry-stdout = "0.33"

Then register the provider with tracer_provider inside with_logging in src/app.rs. For example, this provider prints each span to your terminal while you inspect span attributes locally:

rust
use dust::prelude::*;use opentelemetry_sdk::trace::SdkTracerProvider;Application::configure()    .with_logging(|logging, _| {        let provider = SdkTracerProvider::builder()            .with_batch_exporter(opentelemetry_stdout::SpanExporter::default())            .build();        logging.tracer_provider(provider);    })

When a custom provider is registered, dust-framework uses it instead of the OTEL_* exporter and shuts it down cleanly when your application exits. Because dust-framework installs the provider before the Tokio runtime starts, exporters that require an active Tokio runtime during initialization (such as OTLP over gRPC) will panic.

Troubleshooting tracing

Symptom What to check
No traces arrive The opentelemetry feature is enabled, OTEL_EXPORTER_OTLP_ENDPOINT is set, and OTEL_SDK_DISABLED is not true.
The collector rejects the request The endpoint must be the base URL; the framework appends /v1/traces. Use OTEL_EXPORTER_OTLP_TRACES_ENDPOINT only for a full URL.
Authentication fails Set OTEL_EXPORTER_OTLP_HEADERS, or the traces-specific variant, with the key the vendor expects.
Only some traces arrive A sampler is configured; check OTEL_TRACES_SAMPLER and OTEL_TRACES_SAMPLER_ARG.
A span has no attributes #[tracing::instrument] records arguments by default; skip_all removes them, so add the fields you want with fields(...).
A spawned task's queries are in another trace It was spawned with tokio::spawn; use dust::task::spawn to carry the span.
The process panics at startup with a custom provider A gRPC exporter needs the Tokio runtime; use the OTLP-over-HTTP exporter, which the OTEL_* variables configure.
Traces stop at shutdown Buffered spans flush at exit; a process killed with SIGKILL skips the flush. Stop it with SIGTERM and let the shutdown timeout run.

A trace that looks short may still be complete: the collector samples on arrival, and a parentbased sampler follows the upstream decision. Compare the trace's trace_id with the logs to confirm it is the same request.