# Instrumenting your code


After the [quick start](/docs/rust/getting-started/quick-start#send-logs-and-traces), your requests and SQLx queries are traced. That's a good start, but the slow part of a request is often somewhere in between: a function that does too much, a call to another service, a query through a library Flare doesn't know about. This page shows how to get those into your traces as well.

Everything here uses the `tracing` crate. If you'd like to know how Flare decides what each span is, read [the tracing introduction](/docs/rust/tracing/introduction) first.

If your app doesn't depend on `tracing` directly yet, add it:

```bash
cargo add tracing
```

## Functions

To time a function, add `#[instrument]`. Inside a request, a job or an operation, it shows up as a function span in the trace, labeled with its module and name, like `db::find_post`:

```rust
use tracing::instrument;

#[instrument(skip(pool))]
async fn find_post(pool: &PgPool, id: i64) -> Result<Post, sqlx::Error> {
    sqlx::query_as("SELECT * FROM posts WHERE id = $1")
        .bind(id)
        .fetch_one(pool)
        .await
}
```

The SQLx query inside shows up as a [query span](#sqlx) right below the function span.

`#[instrument]` records every argument as a field, and Flare shows them under Arguments when you click the span. That's useful for an `id`, but not for a connection pool, a large struct, or anything holding a password, token or personal data. Use `skip(...)` to leave arguments out, `skip_all` to record none at all, and `fields(...)` to add your own values:

```rust
#[instrument(skip_all, fields(user_id = %user.id))]
async fn send_invoice(user: &User, invoice: &Invoice) {
    // ...
}
```

`#[instrument]` creates INFO spans, and Flare sends everything at INFO or above. For a function you only want to see locally, use `#[instrument(level = "debug")]`. What happens inside it, like a query, still ends up in the trace. Keep in mind that every span counts against your quota, so small functions that run thousands of times per request are better left out.

## Background work

Not everything your app does is a request. A scheduled task, a loop that syncs data, or a run of a command line tool are just as worth tracing. Flare lists every span without a parent under Operations, so all it takes is an instrumented function that runs outside of any other span:

```rust
use tracing::instrument;

#[instrument]
async fn sync_orders() {
    // ...
}
```

Called from `main` or from a scheduler, `sync_orders` becomes an operation named `sync_orders`. A command line tool works the same way: put `#[instrument]` on the function that does the work, and `#[flareapp::main]` sends the trace before the program exits. For a tool with subcommands, add `flare.span_type = "command"` to the span of each subcommand. Flare then lists each one under Commands instead of Operations, and files its errors and log lines under its name. See [commands](/docs/rust/data-collection/entry-points#commands).

Flare groups operations on the span name and the module of the function, so two `run` functions in different modules each get their own row. Ids, dates, UUIDs and numbers in the span name are replaced by `*`, so `task 1234` and `task 5678` end up on the same row.

### Spawned tasks

Flare sends a trace when its first span closes, and that span only closes when every span below it has closed. So for every task you start with `tokio::spawn`, decide whether it belongs to the trace that started it.

When the task finishes before the request does, for example because the request waits for it, keep it in the trace of the request. Attach the current span to the future:

```rust
use tracing::Instrument;

let handle = tokio::spawn(
    async move {
        // ...
    }
    .in_current_span(),
);

handle.await?;
```

When the task can outlive the request, give it a trace of its own, so it shows up as a separate operation. Start its span without a parent:

```rust
#[instrument(parent = None, skip_all)]
async fn rebuild_search_index(posts: Vec<Post>) {
    // ...
}

tokio::spawn(rebuild_search_index(posts));
```

If you do neither, a task that never calls an instrumented function isn't traced at all. One that does call one starts a new trace for every call.

## Queue consumers

Flare lists a span with the `consumer` kind under Jobs. Set the kind with the `otel.kind` field, and add the name of the queue as `messaging.destination.name`, so Flare can group the jobs per queue:

```rust
#[instrument(
    parent = None,
    skip_all,
    fields(
        otel.kind = "consumer",
        messaging.system = "rabbitmq",
        messaging.operation.type = "process",
        messaging.destination.name = "orders",
    )
)]
async fn handle_order_message(delivery: Delivery) {
    // ...
}
```

`parent = None` gives every message a trace of its own. Without a queue name, Flare names the job after the span. A queue with `messaging.destination.temporary` set to `true` isn't listed, because a temporary queue gets a new name in every process.

Errors and log lines inside the span are filed under the job, see [entry points](/docs/rust/data-collection/entry-points#jobs). They only get the user and context you'd expect when the job has [its own scope](/docs/rust/data-collection/scopes#jobs-and-other-async-work).

### Continuing a trace from a message

To see the request that sent a message and the job that handled it in one trace, send the `traceparent` of the current span along with the message. Give the span that publishes it the `producer` kind. Flare keeps that span in the trace, but doesn't list it:

```rust
use flareapp::tracing::current_traceparent;

#[instrument(skip_all, fields(otel.kind = "producer", messaging.destination.name = "orders"))]
async fn publish_order(channel: &Channel, order: &Order) {
    let traceparent = current_traceparent();

    // Add `traceparent` to the headers of the message, and publish it.
}
```

On the consumer side, create the span yourself, and continue the trace from the header before the span gets any children:

```rust
use flareapp::tracing::SpanExt;
use tracing::Instrument;

let span = tracing::info_span!(
    parent: None,
    "handle order message",
    otel.kind = "consumer",
    messaging.destination.name = "orders",
);

if let Some(traceparent) = delivery.header("traceparent") {
    span.set_parent_from_traceparent(traceparent);
}

process_order(delivery).instrument(span).await;
```

Leave `parent = None` off the functions you call inside this span, unlike `handle_order_message` above. Otherwise they start a trace of their own.

`set_parent_from_traceparent` only works on the first span of a trace, and only while tracing is on. The sampling decision of the producer wins, so a message from a trace that wasn't sampled isn't traced on the consumer side either.

## Database queries

Flare lists every span with a `db.system.name` or `db.query.text` field under Queries. SQLx queries get one without any work on your side. For other database libraries, you create the span yourself.

### SQLx

With the `tracing` feature on, every SQLx query becomes a query span. That works with SQLx 0.9, without any extra feature or setup.

SQLx doesn't create spans itself. After every query, it writes a DEBUG event with the target `sqlx::query`, and the Flare layer turns that event into a span. The span is named after the SQL of the query, has the time the query took and the number of rows it returned, and sits below the span the query ran in, like a request or a function. The event itself doesn't show up as a log row as well.

A few things to know:

- **The event has to reach the Flare layer.** A filter on the whole subscriber, like `.with(LevelFilter::INFO)` or an `EnvFilter` from `RUST_LOG=info`, drops it. Put the filter on your log output only, as in [where your filters go](/docs/rust/logs/introduction#where-your-filters-go). Or let the queries through, with `RUST_LOG=info,sqlx::query=debug`, and accept that your log output prints every query too.
- **A query needs a trace.** A query only becomes a span inside a trace that Flare sends. A query outside of any span, like a migration when your app starts, isn't sent.
- **SQLx doesn't say which database it talks to.** The spans have no database system or name, so Flare groups SQLx queries on their query text only. [The Flare SQLx pool](#the-flare-sqlx-pool) fixes that.
- **No events, no spans.** `log_statements(LevelFilter::Off)` on the connect options of SQLx turns off the events, and the query spans with them.

### The Flare SQLx pool

To get the database in your query spans, and see which queries failed, wrap your SQLx pool in `flareapp::sqlx::Pool`. Turn on the feature for your database, `sqlx-postgres`, `sqlx-mysql` or `sqlx-sqlite`:

```bash
cargo add flareapp --features sqlx-postgres
```

```rust
use flareapp::sqlx::Pool;
use sqlx::postgres::PgPoolOptions;

let pool = Pool::from(PgPoolOptions::new().connect("postgres://localhost/shop").await?);

let users = sqlx::query("SELECT id FROM users").fetch_all(&pool).await?;
```

Run your queries on the wrapper like on the SQLx pool, also in transactions and on connections you take from it. On top of the SQL and the rows, each query span then gets:

- The database system, like `postgresql`, and the name of the database. Flare groups the queries on those too. SQLite has no database name.
- The address and port of the database server, for PostgreSQL and MySQL.
- The error status when the query fails, with the error.

### Other database libraries

Wrap the query in a span of your own:

```rust
use tracing::Instrument;

let query = "SELECT * FROM posts WHERE id = $1";
let span = tracing::info_span!(
    "SELECT posts",
    db.system.name = "postgresql",
    db.namespace = "blog",
    db.query.text = query,
);

let row = client
    .query_one(query, &[&id])
    .instrument(span)
    .await?;
```

Flare groups these queries on the query text, the database system, and the database name in `db.namespace`. Use the [well-known name](https://opentelemetry.io/docs/specs/semconv/registry/attributes/db/#db-system-name) of your database as the system, like `postgresql`, `mysql` or `sqlite`.

For a Redis command, use `redis` as the system, and put the command and its key in the query text, like `GET user:42:profile`. Flare lists it under Database commands, grouped as `GET user:*:profile`.

## Outgoing HTTP calls

Flare lists spans with the `client` kind and an HTTP method under External HTTP. If you use `reqwest`, turn on the `reqwest` feature and build your client with the Flare middleware for `reqwest-middleware`:

```bash
cargo add flareapp --features tracing,reqwest
cargo add reqwest-middleware
```

```rust
let client = reqwest_middleware::ClientBuilder::new(reqwest::Client::new())
    .with(flareapp::reqwest::TracePropagation)
    .build();

let response = client.get("https://api.example.com/orders").send().await?;
```

The middleware is built for reqwest 0.13 and reqwest-middleware 0.5. With other versions, the types don't match and your code doesn't compile.

Every call now gets a span with the method, the full URL and the response status. Flare groups calls on the method, the host and the path, with ids and numbers in the path replaced by `*`. A call that fails, or gets a `4xx` or `5xx` response, gets the error status.

The middleware also adds a `traceparent` header to each request. When the service on the other end sends its traces to Flare too, both sides end up in a single trace. A request that already has a `traceparent` header keeps its own.

With another HTTP client, create the span yourself, and add the header with `current_traceparent()`:

```rust
use flareapp::tracing::current_traceparent;
use tracing::Instrument;

let span = tracing::info_span!(
    "GET api.example.com",
    otel.kind = "client",
    http.request.method = "GET",
    url.full = "https://api.example.com/orders",
);

async {
    let mut request = build_request();

    if let Some(traceparent) = current_traceparent() {
        request.header("traceparent", traceparent);
    }

    send(request).await
}
.instrument(span)
.await;
```

## Panics and errors

Panics and errors need no extra code. A panic inside a span shows up as an exception row in the trace, and marks the span as failed. Errors you report with `report_error` or `report_message` show up as exception rows too, but they don't mark the span as failed, since your code handled them. An `error!` event does mark the span as failed. See [failed requests, jobs and operations](/docs/rust/tracing/introduction#failed-requests-jobs-and-operations).

## Read more

- [The tracing introduction](/docs/rust/tracing/introduction): the lists, how Flare decides what a span is, and the statistics.
- [Aggregations](/docs/protocol/traces/aggregations) in the protocol docs: the exact attributes each list groups on.
