---
title: Follow traces
description: Follow one request through the lunas it called, find slow and failed calls with luna traces, and add your own spans with OpenTelemetry.
related:
  - /observe/read-logs
  - /lunas/call-another-luna
  - /observe/check-status
---

One request can pass through several lunas, a message and a schedule before it is done. A trace ties those calls together, so you can see which call failed and where the time went.

## List recent calls

In your app's folder, run [`luna traces`](/cli/traces).

```bash
luna traces
```

Each line is one call, called a span: when it started, its trace's id, how long it took and the handler, as `List.add`. A call that failed ends with `FAILED`.

Luna does not keep every span. It keeps every call that failed, every call that took 500 ms or more, and one trace in ten of the rest. A trace is kept or dropped as a whole, so a kept trace has all its calls.

## Read one whole trace

Pass a trace's id to read every span in it, however long ago it ran.

```bash
luna traces --trace <TRACE_ID>
```

A trace follows the work a call starts. Calls made with `ctx.call`, messages sent with `ctx.send`, schedules set with `ctx.schedule` and the steps of a durable handler all join the trace of the call that started them. Logs carry the same id, so `luna logs --trace <TRACE_ID>` prints the lines written along the way.

## Find slow and failed calls

Filter the spans to find the calls worth looking at.

```bash
luna traces List --errors --since 6h
```

| Option | Does |
| --- | --- |
| `TYPE` | Only spans of this luna type |
| `--handler` | Only spans of this handler |
| `--errors` | Only calls that failed |
| `--min-ms` | Only calls that took at least this many milliseconds |
| `--since`, `--until` | The window, written as for `luna logs`. The last hour by default |
| `--limit` | At most this many spans, 100 by default |
| `--json` | Each span as a JSON object, one a line |

Luna keeps traces for 7 days, as long as it keeps logs.

## Get a call's trace in code

`ctx.traceId` holds the id of the trace a call belongs to. Return it or send it to another system, and find the trace later with `--trace`.

```ts luna/lunas/list.ts {12}
import { defineLuna, t, table } from "luna";

export const List = defineLuna({
  name: "List",
  visibility: "public",
  key: { id: t.string() },
  schema: { items: table({ id: t.id(), text: t.string() }) },
  handlers: (h) => ({
    add: h({ args: { text: t.string() } }, (ctx, { text }) => {
      ctx.db.items.insert({ text });
      console.log("added", text);
      return { traceId: ctx.traceId };
    }),
  }),
});
```

## Continue a trace from outside

A call can join a trace your own system started. Send the W3C `traceparent` header with it.

```bash
curl -i -X POST "$LUNA_URL/List/groceries/add" \
  -H "luna-key: $LUNA_KEY" \
  -H "traceparent: <TRACEPARENT>" \
  -H "Content-Type: application/json" \
  -d '{"text":"milk"}'
```

The handler's span then sits under your span, in your trace. If the header marks the trace as sampled, Luna keeps it. The response carries a `traceparent` header of its own, naming the handler's span. A header that is not valid is ignored, and the call starts a trace of its own.

## Add your own spans

Luna answers the standard OpenTelemetry API, so you install no exporter. Add `@opentelemetry/api` to your app, then open spans and record metrics as usual.

```ts luna/lunas/list.ts
import { defineLuna, t, table } from "luna";
import { metrics, trace } from "@opentelemetry/api";

const tracer = trace.getTracer("list");
const added = metrics.getMeter("list").createCounter("items.added");

export const List = defineLuna({
  name: "List",
  key: { id: t.string() },
  schema: { items: table({ id: t.id(), text: t.string() }) },
  handlers: (h) => ({
    add: h({ args: { text: t.string() } }, async (ctx, { text }) => {
      const clean = await tracer.startActiveSpan("clean text", async (span) => {
        span.setAttribute("text.length", text.length);
        span.end();
        return text.trim();
      });
      ctx.db.items.insert({ text: clean });
      added.add(1);
    }),
  }),
});
```

Your spans sit under the handler's span, and calls made inside a span sit under it. In a trace that is not kept, your span is kept only if it fails or takes 500 ms or more. Metrics show in `luna status List`, as [Check status](/observe/check-status) shows.

## Pass the trace to another service

To carry the trace into a service you call with `fetch`, put the current context in the request's headers. Import `context` and `propagation` from `@opentelemetry/api`.

```ts luna/lunas/shop.ts
notify: h({ args: { text: t.string() } }, async (ctx, { text }) => {
  const headers: Record<string, string> = { "content-type": "application/json" };
  propagation.inject(context.active(), headers);
  const body = JSON.stringify({ text });
  await fetch("https://example.com/hooks", { method: "POST", headers, body });
}),
```

`propagation.inject` adds a `traceparent` header. Luna does not add one to `fetch` on its own.

## Next steps

- [Read logs](/observe/read-logs) shows the lines a traced call wrote.
- [Call another luna](/lunas/call-another-luna) covers the calls and messages a trace follows.
- [Check status](/observe/check-status) shows latency for each handler.
