Database Tracing

Get spans for SQL queries in Rust with sqlx, diesel, and tokio-postgres — what each driver emits by itself, query spans with db.* attributes, and passing traceparent to PostgreSQL for pg_tracing.

Rust database drivers do not ship OpenTelemetry instrumentation, so there is no switch that produces a span per query. What you get depends on the driver: sqlx emits a tracing event for every statement, diesel exposes a hook, and tokio-postgres has neither. In each case a query span is a few lines of tracing code, and the tracing-opentelemetry layer from Installation exports it.

Checked with sqlx 0.8, diesel 2.3, and tokio-postgres 0.7.

What each driver gives you

DriverBuilt inTo get a span per query
sqlxOne tracing event per statement (target sqlx::query), no spansWrap the call in a span
dieselThe Instrumentation hook with start and finish events, no output by defaultCreate spans in the hook
tokio-postgresNo spans and no hookWrap the call in a span

sqlx statement events

sqlx logs each statement as a tracing event with the fields summary, db.statement, rows_affected, rows_returned, and elapsed. The level is DEBUG by default, and statements slower than one second are logged at WARN. Because it is an event, not a span, two things happen to it:

  • tracing-opentelemetry attaches it to the span that was current when the query ran, as a span event. The server span of a request lists its statements, without a duration bar of their own.
  • The log bridge exports it as a log record.

Both depend on your filters letting sqlx::query through at that level. To change the level, or silence the events once you have spans:

use std::time::Duration;
 
use sqlx::postgres::PgConnectOptions;
use sqlx::ConnectOptions;
use tracing::log::LevelFilter;
 
let options = "postgres://localhost/shop"
    .parse::<PgConnectOptions>()?
    .log_statements(LevelFilter::Debug)
    .log_slow_statements(LevelFilter::Warn, Duration::from_millis(500));

Query spans

Create a span around the query and attach it with .instrument(). The span becomes a child of whatever span is current, normally the request's server span.

use tracing::{field::Empty, Instrument};
 
async fn find_user(pool: &sqlx::PgPool, id: i64) -> sqlx::Result<Option<(i64, String)>> {
    const SQL: &str = "SELECT id, name FROM users WHERE id = $1";
    let span = tracing::info_span!(
        "SELECT users",
        otel.kind = "client",
        otel.status_code = Empty,
        db.system.name = "postgresql",
        db.namespace = "shop",
        db.operation.name = "SELECT",
        db.collection.name = "users",
        db.query.text = SQL,
        error.type = Empty,
    );
 
    let result = sqlx::query_as(SQL)
        .bind(id)
        .fetch_optional(pool)
        .instrument(span.clone())
        .await;
 
    if let Err(err) = &result {
        span.record("otel.status_code", "ERROR");
        span.record("error.type", tracing::field::display(err));
    }
    result
}

The attribute names follow the OpenTelemetry database conventions. Name the span after the operation and table, and keep db.query.text to the statement with placeholders, never with the bound values.

The same pattern works for tokio-postgres: build the span, then client.query(SQL, &[&id]).instrument(span).await.

NOTE — Keep the span and the query together

.instrument(span) enters the span each time the future is polled, which is correct across .await points. Holding a span.enter() guard across an .await is not: the span leaks onto whatever task the thread runs next.

diesel

diesel calls an Instrumentation hook around every query. Register a constructor once at startup; each new connection gets its own instance.

use diesel::connection::{set_default_instrumentation, Instrumentation, InstrumentationEvent};
use tracing::field::Empty;
 
fn query_spans() -> Option<Box<dyn Instrumentation>> {
    let mut current: Option<tracing::Span> = None;
    Some(Box::new(move |event: InstrumentationEvent<'_>| match event {
        InstrumentationEvent::StartQuery { query, .. } => {
            current = Some(tracing::info_span!(
                "diesel.query",
                otel.kind = "client",
                otel.status_code = Empty,
                db.system.name = "postgresql",
                db.query.text = %query,
            ));
        }
        InstrumentationEvent::FinishQuery { error, .. } => {
            if let Some(span) = current.take() {
                if error.is_some() {
                    span.record("otel.status_code", "ERROR");
                }
            }
        }
        _ => {}
    }))
}
 
set_default_instrumentation(query_spans).expect("failed to set diesel instrumentation");

The span starts when it is created and ends when it is dropped, so it covers the query. Its parent is the span that is current on the thread running the query. diesel is synchronous, so in an async server the query usually runs in spawn_blocking, where no span is current. Carry the request span over:

let span = tracing::Span::current();
let user = tokio::task::spawn_blocking(move || span.in_scope(|| load_user(&mut conn, id))).await?;

Into PostgreSQL

A client span shows how long the application waited. To see what PostgreSQL did during that time, as spans in the same trace, the database needs the trace context. The pg_tracing extension reads it from a SQL comment, so append traceparent to the statement:

use std::collections::HashMap;
 
use opentelemetry::global;
use tracing_opentelemetry::OpenTelemetrySpanExt;
 
fn with_traceparent(sql: &str) -> String {
    let cx = tracing::Span::current().context();
    let mut carrier = HashMap::new();
    global::get_text_map_propagator(|p| p.inject_context(&cx, &mut carrier));
    match carrier.get("traceparent") {
        Some(traceparent) => format!("{sql} /*traceparent='{traceparent}'*/"),
        None => sql.to_owned(),
    }
}

Call it inside the query span, so the database spans become children of that span:

async {
    let sql = with_traceparent("SELECT count(*) FROM orders");
    sqlx::query(&sql).persistent(false).fetch_one(pool).await
}
.instrument(span)
.await

CAUTION — The comment changes the statement text

Every traced statement has a different text, and sqlx caches prepared statements by text. .persistent(false) keeps commented statements out of that cache. Add the comment to the queries you want to see inside the database, not to every statement.

pg_tracing records spans only for statements that arrive with a sampled traceparent, and it is not available on managed PostgreSQL services. Deployment options and what each one covers are in PostgreSQL.

Next steps

  • PostgreSQL — server-side spans, logs, and query statistics from the database.
  • Deployment — batching and flushing in production.