Attribute Macro instrument_query

Source
#[instrument_query]
Expand description

Specialized version of tracing::instrument for recording SQLx queries to Datadog.

Accepts all arguments tracing::instrument accepts, but patches in extra fields.

By default, expects a function argument called db that has a reference to the connection, but accepts a db parameter with an alternative identifier.

For optimal results, the db.statement span tag should be set to the text of the SQL query executed.

#[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
}