#sqlx #tracing #open-telemetry #database #derive-debug #sql-query

macro sqlx-datadog

SQLx instrumentation for tracing to Datadog APM via OpenTelemetry

1 unstable release

Uses new Rust 2024

new 0.1.0 Mar 16, 2025

#146 in #open-telemetry

MIT/Apache

15KB
69 lines

SQLx-Datadog

This crate provides a drop-in replacement for tracing::instrument meant for instrumenting SQLx queries with tracing for use with tracing-opentelemetry.

It automatically injects span tags for Datadog to correctly identify the span as a SQL query and set relevant attributes.

This is what it looks like in action:

use sqlx::Execute;
use sqlx_datadog::instrument_query;

#[derive(Debug, sqlx::FromRow)]
struct User { name: String, email: String }

#[instrument_query(skip(db))]
async fn fetch_user(db: &sqlx::MySqlPool, user_id: i64) -> Result<User, sqlx::Error> {
    let query = sqlx::query_as("SELECT name, email FROM users WHERE id = ? LIMIT 1");
    tracing::Span::current().record("db.statement", query.sql().trim());
    query.bind(user_id).fetch_one(db).await
}

Current Limitations

For the time being, it still requires manually setting the query text as shown in the example, and it does not inject the distributed tracing comment into the query yet.

It probably does not work with SQLite, as SQLite's ConnectOptions are quite different from both MySQL's and Postgres'.

Dependencies

~205–640KB
~15K SLoC