skip to content

In Rust's tracing crate, what does `#[instrument(skip(db), fields(order_id = %id))]` on `async fn charge(db: &Db, id: OrderId, amount_cents: u64)` record, and why skip `db`?

level: middleimportance: should knowfreq 45%

answer

  1. a span per call
  2. arguments become span fields
  3. Debug unless the type is a Value
  4. percent is Display, question mark Debug
  5. skip what has no Debug

basics

~20 s

Each call gets an INFO span named charge, entered while the future runs. Arguments become fields (id with Debug, amount_cents as a number) plus order_id via Display. skip(db) leaves out db, whose type has no Debug impl, which would otherwise fail with E0277.

solid answer

~40 s

`#[instrument]` wraps `charge` so every call creates a span named after the function, at `INFO` unless `level` says otherwise; on an `async fn` it attaches the span with `Instrument::instrument`, so the span is entered on each poll and exited at each `.await`. By default every argument becomes a span field: primitive types implementing tracing's `Value` keep their type, everything else is recorded with `Debug`. `skip(db)` removes `db`, which matters because `Db` has no `Debug` impl and the macro would otherwise fail with E0277. `fields(order_id = %id)` adds a field recorded with `Display` (`%`); `?` would use `Debug`. Because `order_id` is not named `id`, `id` is still recorded too, so the span carries both `id=OrderId(42)` and `order_id=ord_42`; write `skip(db, id)` or `skip_all` to keep one. Events inside `charge` are reported within the span.

code

rust · 27 lines
rust
use std::fmt;
use tracing::{info, instrument, warn};

struct Db; // a connection pool: no Debug impl

#[derive(Debug)]
struct OrderId(u64);

impl fmt::Display for OrderId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ord_{}", self.0)
    }
}

#[instrument(skip(db), fields(order_id = %id))]
async fn charge(db: &Db, id: OrderId, amount_cents: u64) -> Result<(), String> {
    let _ = db;
    info!(amount_cents, "charging card");
    warn!(retry = ?Some(2), "gateway slow");
    Ok(())
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt().with_ansi(false).without_time().init();
    charge(&Db, OrderId(42), 1999).await.unwrap();
}

go deeper

for a junior

Recall that #[instrument] makes a span per call named after the function, and that its arguments show up as fields on every log line inside it.

for a middle

Explain the defaults (INFO, function name, every argument via Value or Debug), what skip and skip_all do, and the % for Display versus ? for Debug sigils.

for a senior

Review instrumented handlers for secrets and huge Debug output in arguments, prefer skip_all with explicit fields on hot paths, and catch duplicated fields like id beside order_id.

for a principal

Set the team convention: which fields every request span carries, which argument types are never recorded, and whether skip_all is the default for handlers that receive credentials.

## What `#[instrument]` generates `tracing` records two kinds of data: **events**, which happen at one moment (`info!`, `warn!` and the others), and **spans**, which have a beginning and an end and give context to everything that happens inside them. `#[tracing::instrument]` is an attribute macro (from the `tracing-attributes` crate, re-exported by `tracing` under its default `attributes` feature) that creates a span every time a function is called. Its defaults, from the macro's own documentation: - the span's **name** is the function's name (`charge`); override it with `name = "..."`; - its **level** is `INFO`; override it with `level = "debug"` or `level = Level::DEBUG`; - its **target** is the module path; override it with `target = "..."`; - **every argument** becomes a field. Arguments whose types implement tracing's `Value` trait (integers, `bool`, `&str` and the other primitives) are recorded as typed values; anything else is recorded through its `fmt::Debug` implementation. For an ordinary function the macro enters the span with a guard for the length of the body. For an **`async fn`** it builds the span and wraps the body's future with `Instrument::instrument`, so the span is entered each time the future is polled and exited whenever it yields at an `.await`. ## The payment handler ```rust #[instrument(skip(db), fields(order_id = %id))] async fn charge(db: &Db, id: OrderId, amount_cents: u64) -> Result<(), String> { let _ = db; info!(amount_cents, "charging card"); warn!(retry = ?Some(2), "gateway slow"); Ok(()) } ``` With a `fmt` subscriber, the two events print as: ```plaintext INFO charge{id=OrderId(42) amount_cents=1999 order_id=ord_42}: billing: charging card amount_cents=1999 WARN charge{id=OrderId(42) amount_cents=1999 order_id=ord_42}: billing: gateway slow retry=Some(2) ``` Each event line carries the span's name and fields in braces, then the target (`billing`), then the event's own message and fields. The events never mention `order_id` themselves: they **inherit** it because they happen while the `charge` span is entered. That is the point of instrumenting the handler. Every event inside it, including events from library code the handler calls, is reported in the context of one payment, without each call site repeating the identifier. A JSON formatter shows the same data as a `span` object beside the event's `fields`, so a log query can select every line for one order. ## Why `skip(db)` is there `db` is a connection pool with no `Debug` implementation. Because the macro records every argument with `Debug` by default, removing `skip(db)` stops the build: ```plaintext error[E0277]: `Db` doesn't implement `Debug` ``` The macro's documentation gives the two reasons to skip an argument: its type **does not implement `Debug`**, or its `Debug` output is **verbose or costly**. A third reason matters in a payment service: an argument such as a card token or an API key should never reach the logs at all. `skip(a, b)` takes several names, and `skip_all` records no arguments, leaving `fields(...)` to name exactly what to keep. ## `fields`, `%` and `?` `fields(...)` adds key-value pairs whose values are expressions over the arguments. Two **sigils** choose the formatting: | Written | Recorded with | Example output | |---|---|---| | `order_id = %id` | `fmt::Display` | `order_id=ord_42` | | `order_id = ?id` | `fmt::Debug` | `order_id=OrderId(42)` | | `amount_cents` (an integer) | its `Value` impl | `amount_cents=1999` | The same sigils work in events: `warn!(retry = ?Some(2), "...")`. Field names may be dotted (`http.method`), and a field declared as `tracing::field::Empty` can be filled later with `Span::current().record(...)`. One detail catches people out. The docs say a field with the **same name** as an argument replaces that argument's default recording. `order_id` is not `id`, so `id` is still recorded with `Debug`, and the span ends up with the order identifier twice. Fix it in one of three ways: 1. `skip(db, id)` and keep `fields(order_id = %id)`; 2. `skip_all, fields(order_id = %id, amount_cents)`, naming every field explicitly; 3. rename the parameter so the field and the argument share a name. ## Return values and errors `ret` emits an event carrying the return value (with `Debug`, at the span's level); `err` emits an `ERROR` event when the function returns `Err`, using the error's `Display`. `err(Debug)` and `ret(Display)` switch the formatting, and `err(level = Level::WARN)` changes the level. ## Common mistakes - Forgetting that every argument is recorded: a large request body or a secret ends up in every log line. - Reading `%` as `Debug`: `%` is `Display`, `?` is `Debug`. - Assuming `fields(order_id = %id)` replaces `id`: only a field named `id` would. - Expecting `#[instrument]` on a `const fn` to work: the macro rejects it.

  • What do `err` and `ret` add to `#[instrument]`, and at what level do they fire?
    `ret` emits an event with the function's return value, recorded with `Debug` (or `Display` via `ret(Display)`), at the same level as the span. `err`, for a function returning `Result`, emits an event when it returns `Err`, using the error's `Display` by default and the `ERROR` level unless you write `err(level = ...)`. They can be combined as `#[instrument(err, ret)]`.
  • How do you put a value on the span that is only known halfway through `charge`, such as the gateway's status code?
    Declare the field up front as empty, `#[instrument(fields(status = tracing::field::Empty))]`, then call `tracing::Span::current().record("status", code)` once you have it. A span's field names are fixed when it is created; recording an undeclared field raises no error and silently has no effect, so declaring it empty reserves the slot.

  • In tracing, % formats a field with Debug and ? with Display.
  • #[instrument] records only the fields you list, never the arguments.
  • An argument without Debug is silently left out of the span.
  • fields(order_id = %id) replaces the default recording of id.
  • #[instrument] creates its span at DEBUG unless you set a level.