---
title: Record every run with otel.Install
description: One line, defer otel.Install()(), records every event, transcript batch and span of every run to a local SQLite file with no network; read it back through otel.LocalDB() and obsdb, or start a private pipeline in tests with otel.Start.
url: https://weftgo.dev/docs/observe/recording/
type: how-to
sources:
  - 'weft/otel/pipeline.go:224-236 (Start: a Studio or a Local named in code, NoDiscovery and WEFT_STUDIO_URL switch the discovery read off), 276-279 (joined the running Studio); weft/otel/options.go:127-139 (NoDiscovery), 214-227 (Local); weft/CHANGELOG.md:125, 154 (0.19.0: NoDiscovery; an explicit Local switches the discovery file off)'
  - weft/AGENTS.md:195-201 (block 6), 597-598, 618, 631-634 (block 9)
  - weft/otel/doc.go (package documentation)
  - 'weft/otel/pipeline.go:218-312 (Start: explicit and environment destinations combined; errNoDestinations), 342-371 (Install: never fails, falls back to Local(""), the returned function''s 5 s shutdown)'
  - weft/otel/pipeline.go:43-73 (Pipeline, TracerProvider, LoggerProvider), 109-113 (LocalDB, StudioEndpoint), 120 (ForceFlush), 154 (Shutdown's order), 392 (defaultHeartbeat 10 s), 857-879 (LocalDB, StudioEndpoint)
  - weft/otel/options.go:13 (Option), 76 (Heartbeat), 100 (NoEnv), 206 (NoGlobal), 221 (Local)
  - weft/otel/config.go:157-164 (defaultLocalPath, $WEFT_DB or .weft/weft.db)
  - weft/otel/env.go:11-62 (environment destinations), 151-176 (discoverStudio)
  - weft/otel/pipeline.go:218-236 (Start reads the environment and the discovery file once, while it builds the destinations); weft/cmd/weft/dev.go:156-183 (weft dev binds Studio, then starts the app with WEFT_STUDIO_URL)
  - weft/obsdb/db.go:998 (InterruptedAfter = 30 s)
  - weft/obsdb/sqlite/write.go:474, 496 (spans and records INSERT OR IGNORE), 530 (other_logs plain INSERT)
  - weft/docs/record-contract.md:486-537 (log records, the storage key), 851-885 (heartbeat)
  - weft/docs/adr/0024-observability-data.md
  - weft/README.md:319-341 (Recording runs)
  - 'weft/otel/example_test.go:25-60 (ExampleInstall: NoEnv, Local, a scripted run, shutdown, sqlite.Open, Runs)'
  - weft/CHANGELOG.md:3213, 3217, 3348, 4331, 4352, 4792, 4800
  - docs-site/examples/recording/main.go, main_test.go TestRecording, TestRecordsLocally, TestZeroOptionInstall, TestHeartbeats
---

# Record every run with otel.Install

[`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) starts weft's observability pipeline and registers it as the process's OpenTelemetry providers. With no option and no destination named by the environment, `defer otel.Install()()` writes every run to the [local sink](https://weftgo.dev/docs/reference/glossary/#local-sink), a SQLite file at `./.weft/weft.db`, content on, no network: each event, transcript batch and span is written as it happens. [`otel.LocalDB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LocalDB) hands back the database, and the recorded run reads back through [`obsdb.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB).

Record a run and read it back, in `recording/main.go`:

```go title="recording/main.go"
defer otel.Install(otel.Local(""))() // the local sink: $WEFT_DB, else ./.weft/weft.db

agt := weft.New(script(), weft.Name("support-bot"), lookup)
res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
if err != nil {
	return err
}

db := otel.LocalDB() // the pipeline's own handle on the sink
rec, err := db.Run(ctx, res.ID)
if err != nil {
	return err
}
fmt.Fprintln(w, rec.Agent, rec.Status, "steps:", rec.Steps,
	"events:", rec.EventCount, "transcript batches:", rec.MessageCount)

page, err := db.Events(ctx, res.ID, -1, 50) // -1: from the first event
if err != nil {
	return err
}
var types []string
for _, e := range page.Events {
	types = append(types, eventType(e.Event))
}
fmt.Fprintln(w, strings.Join(types, " "))

spans, err := db.RunSpans(ctx, res.ID)
if err != nil {
	return err
}
for _, s := range spans {
	fmt.Fprintln(w, "span:", s.Name)
}
```

[recording/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/recording/main.go)

The agent needs no option: the core reports through the global OTel providers, and `Install` registered them. `otel.Local("")` names the local sink explicitly, which keeps it when the environment adds a destination ([below](#what-the-environment-adds)). The run is in the database as soon as `Generate` returns, because the local sink writes synchronously.

## Install

> **Diagram:** Your app runs agents with agt.Generate; every run leaves as OpenTelemetry spans and log records. otel.Install starts the pipeline and sends them to every destination at once; with no options and no destination named by the environment it writes the local sink only. otel.Local writes .weft/weft.db synchronously; otel.Studio exports OTLP over HTTP to a running weft studio. The Inspector reads them back: embedded with studio.Handler over otel.LocalDB(), or served by weft studio.

`otel.Install(opts...)` takes [`otel.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Option) values: the destinations, the content policy and the pipeline's settings. It returns a function that flushes every destination and shuts the pipeline down; call it on exit, hence `defer otel.Install(...)()`. That function waits at most 5 seconds. `Install` never panics and never fails the program: a destination that cannot be built is logged at WARN and skipped. The package example, [`ExampleInstall`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#example-Install), installs a local sink under `otel.NoEnv()`, runs a scripted agent, calls the returned function, and reopens the file with `obsdb/sqlite` to read the run back.

[`otel.Local(path)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Local) is the local sink: `obsdb/sqlite` at `path`, or at `$WEFT_DB`, else `./.weft/weft.db`, when `path` is `""`. It writes synchronously, so nothing emitted is lost, and it holds content: message text, tool arguments and results, the system prompt and the catalog.

What the pipeline receives from each run:

- **Spans.** One `invoke_agent` span per run, one `chat` span per model call, one `execute_tool` span per tool call, and an `attempt` span under `chat` for each try that `mw.Retry`, `mw.Fallback` or an adapter reports; all with ids, names, counts, durations and error types but never content. [Use your own OpenTelemetry SDK](https://weftgo.dev/docs/observe/opentelemetry/#spans) lists their attributes.
- **Event records.** Every durable event, from `run_start` to `run_finish`, is one log record whose body is the event's wire JSON, numbered by `weft.event.pos` from 0. Deltas (`text_delta`, `reasoning_delta`, `tool_args_delta`) are records on their own counter, `weft.delta.pos`, so dropping them never opens a hole in the durable sequence. The local sink counts deltas and stores none.
- **Transcript records.** A `weft.messages` record at each point the transcript grows: the input at run start, each assistant message, each tool message, each steered batch, the tool message a resume builds. Concatenated, their bodies equal `RunResult.Messages` byte for byte. They are emitted only when some destination takes content, and none after the run's context ends.
- **Request records.** What each model call was given: the request, the system prompt and the tool catalog, by hash ([the record contract §4](https://github.com/weftgo/weft/blob/v0.20.2/docs/record-contract.md#4-log-records)).

Tool-call arguments that are not JSON do not drop records: the `tool_start` event, the assistant's transcript batch and later input records carry the raw bytes as a JSON string.

A store keys every record on (run id, kind, position), so a record exported twice is stored once. Each positioned kind's positions run from 0 without gaps (heartbeats and `thread`'s compaction markers have no position); a hole below the highest position is a lost record, and Studio badges it `gap`.

### Read a run back

[`otel.LocalDB()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LocalDB) returns the installed pipeline's `obsdb.DB`: the same handle the local sink writes. It is nil before `Install`, after its shutdown, and in a pipeline without a local sink. The interface reads what Studio reads: [`Runs`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB) and `Run` (the run row, with its derived status and its subagent children), `Events` (positioned pages; `-1` reads from the first), `Transcript`, `RunSpans`, `OtherLogs` (your [app log lines](https://weftgo.dev/docs/observe/app-logs/)), sessions and traces.

After the process exits, the file reopens with [`sqlite.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#Open), and `weft studio` serves it: its default database is the same `./.weft/weft.db`.

To serve Studio inside the app over the same handle, mount [`studio.Handler`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Handler)`(`[`studio.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#DB)`(otel.LocalDB()))`. Studio then sees each run live as the pipeline writes it ([Run Studio](https://weftgo.dev/docs/observe/studio/setup/)).

[`otel.StudioEndpoint()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#StudioEndpoint) returns the URL and token of the installed pipeline's Studio destination, `""` without one. `weft/runtime` dials that Studio by default ([Connect your app to the playground](https://weftgo.dev/docs/observe/playground/connect/)).

### What the environment adds

`Install` and `Start` read the environment for extra destinations: `WEFT_STUDIO_URL` adds a Studio, `OTEL_EXPORTER_OTLP_ENDPOINT` an OTLP endpoint, and with `WEFT_STUDIO_URL` unset, the [discovery file](https://weftgo.dev/docs/reference/glossary/#discovery-file) of a running `weft studio` or `weft dev` adds that Studio. [Environment variables](https://weftgo.dev/docs/reference/env/#weft-studio-url) lists every rule. Three of them shape this page:

- A zero-option `otel.Install()` writes the local sink only when the environment adds nothing. When it adds a destination, the pipeline exports there **instead**, and `otel.LocalDB()` is nil. Pass `otel.Local("")` to keep the local sink beside an environment destination, as the example does.
- A store named in code turns discovery off. Since 0.19.0 an explicit `otel.Local`, like an explicit `otel.Studio`, writes only to the stores it names and the environment's, never into a running `weft studio` it found on disk. To write to both, name both: `otel.Install(otel.Local(path), otel.Studio(url, tok))`, or set `WEFT_STUDIO_URL`. A pipeline that joins a discovered Studio says so in one INFO line, `weft/otel: joined the running Studio`; [`otel.NoDiscovery()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#NoDiscovery), `WEFT_DISCOVERY=off` or [`otel.NoEnv()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#NoEnv) stops it ([The discovery file](https://weftgo.dev/docs/observe/weft-dev/#the-discovery-file)).
- The environment and the discovery file are read once, when `Install` or `Start` builds the pipeline. A Studio started later is never joined.

## Start in tests

[`otel.Start`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Start) is `Install` that returns errors: any destination that fails to build fails the call, and what was already built is shut down. [`otel.NoGlobal()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#NoGlobal) leaves the OTel globals alone, so you pass the pipeline's providers to the agent. A test that records to its own database, in `recording/main_test.go`:

```go title="recording/main_test.go"
p, err := otel.Start(ctx,
	otel.NoEnv(),    // no WEFT_* / OTEL_* variable or discovery file adds a destination
	otel.NoGlobal(), // the OTel globals stay as they were
	otel.Local(filepath.Join(dir, "weft.db")),
)
if err != nil {
	t.Fatal(err)
}
defer func() { _ = p.Shutdown(ctx) }()

agt := weft.New(script(), weft.Name("support-bot"), lookup,
	weft.TracerProvider(p.TracerProvider()), // hand the agent this pipeline's providers
	weft.LoggerProvider(p.LoggerProvider()),
)
res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
if err != nil {
	t.Fatal(err)
}
rec, err := p.LocalDB().Run(ctx, res.ID)
if err != nil {
	t.Fatal(err)
}
if rec.Status != obsdb.StatusSucceeded || rec.Steps != 2 {
	t.Fatalf("recorded %s in %d steps, want succeeded in 2", rec.Status, rec.Steps)
}
```

[recording/main_test.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/recording/main_test.go)

`otel.NoEnv()` ignores the `WEFT_*` and `OTEL_*` destination variables and the discovery file, so no destination joins the test from outside. Under `NoGlobal`, `otel.LocalDB()` and `otel.StudioEndpoint()` see no pipeline; use the methods of the [`*otel.Pipeline`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Pipeline):

| Method | Returns or does |
|---|---|
| [`TracerProvider()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Pipeline.TracerProvider) | the pipeline's `*sdktrace.TracerProvider`, for `weft.TracerProvider` |
| [`LoggerProvider()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Pipeline.LoggerProvider) | the pipeline's `*otel.LoggerProvider`, for `weft.LoggerProvider` |
| [`LocalDB()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Pipeline.LocalDB) | the local sink's `obsdb.DB`; nil without one |
| [`StudioEndpoint()`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Pipeline.StudioEndpoint) | the Studio destination's URL and token; `""` without one |
| [`SlogHandler(next)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Pipeline.SlogHandler) | a `slog.Handler` bridged to this pipeline ([app logs](https://weftgo.dev/docs/observe/app-logs/#bridge-slog)) |
| [`ForceFlush(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Pipeline.ForceFlush) | flushes every destination at once, each on its own goroutine, so a hung destination costs only its own data |
| [`Shutdown(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Pipeline.Shutdown) | stops heartbeats, flushes every destination in parallel (5 s budget), shuts the providers down, closes the local database last; runs once, every wait bounded by `ctx` |

## Heartbeats

A run that waits 45 seconds on a tool emits nothing for 45 seconds. So the pipeline's run tracker emits one `weft.heartbeat` record per open run every 10 seconds, carrying the run's id and identity attributes and no body. A reader moves the run's last-seen time on each one and never stores it. Three missed intervals, 30 seconds of silence, is what `obsdb` reads as `interrupted`: a crashed process stops beating, and its runs stop reading `running`.

[`otel.Heartbeat(d)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Heartbeat) sets the interval; `0` or less turns heartbeats off. Keep it well under 30 seconds: the 30-second rule is fixed in `obsdb` (`InterruptedAfter`), not three times your interval, so with a longer interval a quiet run reads `interrupted` between beats. A run that is sampled out and then fails or is cancelled leaves the tracker too, so it never heartbeats forever. A destination that has lost records adds its count, `weft.records.dropped`, to its copy of each heartbeat ([queues](https://weftgo.dev/docs/observe/destinations/#queue-size-and-blocking)).

## Complete example

```go title="recording/main.go"
// Command recording runs the example of the guide "Record every run with
// otel.Install": go run ./recording. The model is scripted with
// wefttest, so it runs offline; the run is recorded to ./.weft/weft.db
// (or $WEFT_DB) and read back from it.
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"os"
	"strings"

	"github.com/weftgo/weft"
	"github.com/weftgo/weft/otel"
	"github.com/weftgo/weft/wefttest"
)

// LookupInput is the lookup tool's argument.
type LookupInput struct {
	OrderID string `json:"order_id" jsonschema:"the order to look up"`
}

var lookup = weft.Tool("lookup_order", "Look up an order by ID.",
	func(_ context.Context, in LookupInput) (string, error) {
		return "order " + in.OrderID + " has shipped", nil
	})

// script is a two-step dialogue: one tool call, then an answer.
func script() *wefttest.Model {
	return wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}),
		wefttest.Say("Order 1234 has shipped."),
	)
}

func main() {
	if err := run(context.Background(), os.Stdout); err != nil {
		log.Fatal(err)
	}
}

// run records one run with otel.Install and reads it back from the
// local sink.
func run(ctx context.Context, w io.Writer) error {
	defer otel.Install(otel.Local(""))() // the local sink: $WEFT_DB, else ./.weft/weft.db

	agt := weft.New(script(), weft.Name("support-bot"), lookup)
	res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
	if err != nil {
		return err
	}

	db := otel.LocalDB() // the pipeline's own handle on the sink
	rec, err := db.Run(ctx, res.ID)
	if err != nil {
		return err
	}
	fmt.Fprintln(w, rec.Agent, rec.Status, "steps:", rec.Steps,
		"events:", rec.EventCount, "transcript batches:", rec.MessageCount)

	page, err := db.Events(ctx, res.ID, -1, 50) // -1: from the first event
	if err != nil {
		return err
	}
	var types []string
	for _, e := range page.Events {
		types = append(types, eventType(e.Event))
	}
	fmt.Fprintln(w, strings.Join(types, " "))

	spans, err := db.RunSpans(ctx, res.ID)
	if err != nil {
		return err
	}
	for _, s := range spans {
		fmt.Fprintln(w, "span:", s.Name)
	}
	return nil
}

// eventType reads the "type" discriminator of an event's wire JSON.
func eventType(body []byte) string {
	var ev struct {
		Type string `json:"type"`
	}
	_ = json.Unmarshal(body, &ev)
	return ev.Type
}
```

[recording/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/recording/main.go)

From `docs-site/examples`:

```sh
go run ./recording
go test ./recording
```

```text
support-bot succeeded steps: 2 events: 8 transcript batches: 4
run_start step_start tool_start tool_finish step_finish step_start step_finish run_finish
span: invoke_agent support-bot
span: chat script
span: execute_tool lookup_order
span: chat script
```

The run took two steps, so its row reads 2. Eight durable events, four transcript batches (the prompt, the assistant's tool call, the tool result, the answer) and four spans were written. `go run` leaves the recording in `./.weft/weft.db`; `weft studio`, started in the same directory, serves it.

## Best practices & gotchas

- **Name the local sink when you read it.** With `WEFT_STUDIO_URL`, `OTEL_EXPORTER_OTLP_ENDPOINT` or a running `weft studio`, a zero-option `Install` writes no local sink, and `otel.LocalDB()` is nil; `studio.DB(nil)` makes `studio.New` panic. `otel.Install(otel.Local(""))` keeps it. (Source: `otel/pipeline.go:218-238, 342-351`; `TestZeroOptionInstall`)
- **Call the function `Install` returns.** It flushes the batch queues of the exporting destinations; a program that exits without it loses what was still queued. (Source: `otel.Install` godoc; `otel/pipeline.go:364-369`)
- **Use `Start` where a failure must show.** `Install` logs a destination that fails to build and goes on without it; `Start` returns the error. (Source: `otel.Start` godoc)
- **Name the store in a test, and add `NoEnv` to isolate it.** `otel.Start(ctx, otel.Local(p), otel.NoGlobal())` no longer joins a running `weft studio` through the discovery file (before 0.19.0 it did, and wrote every run twice), but the environment's destinations still apply: a `WEFT_STUDIO_URL` or `OTEL_EXPORTER_OTLP_ENDPOINT` set in the shell still receives the test's runs. Add `otel.NoEnv()` to write only to `p`, as the example's test does. A pipeline whose only destinations are `otel.OTLP`, `Datadog`, `Langfuse` or `Exporters` also still reads the discovery file: `otel.NoDiscovery()` stops that alone. (Source: `otel/pipeline.go:224-236`; CHANGELOG.md:154)
- **Start `weft studio` before the app, or restart the app.** The discovery file is read once, in `Install` or `Start`. An app started before Studio, or still running when Studio comes back on another port, never exports to it, and nothing above Debug says so. `weft dev` is not affected: it binds Studio before it starts the app, passes `WEFT_STUDIO_URL`, and starts a new process on each reload. (Source: `otel/pipeline.go:218-236`; `otel/env.go:151-176`; `cmd/weft/dev.go:156-183`)
- **Keep `Heartbeat(d)` well under 30 s.** `obsdb.InterruptedAfter` is a fixed 30 s whatever the interval; a slower beat makes a quiet run read `interrupted`. (Source: `obsdb/db.go:998`; `otel.Heartbeat` godoc)
- **Do not expect deltas in the database.** Deltas are counted on the run row (`DeltaCount`) and never stored. (Source: `obsdb.DB` godoc, `Write`)

## See also

- [Send records to Studio, Datadog, Langfuse or any OTLP backend](https://weftgo.dev/docs/observe/destinations/): more destinations, each with its own content policy
- [Run Studio: embedded, local binary or hosted](https://weftgo.dev/docs/observe/studio/setup/)
- [Bridge your app's slog lines into runs](https://weftgo.dev/docs/observe/app-logs/)
- [Environment variables](https://weftgo.dev/docs/reference/env/)
- [The record contract](https://github.com/weftgo/weft/blob/v0.20.2/docs/record-contract.md): every span, record and attribute

Symbols used: [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) · [`otel.Start`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Start) · [`otel.Option`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Option) · [`otel.Local`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Local) · [`otel.LocalDB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LocalDB) · [`otel.StudioEndpoint`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#StudioEndpoint) · [`otel.NoEnv`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#NoEnv) · [`otel.NoGlobal`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#NoGlobal) · [`otel.Heartbeat`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Heartbeat) · [`otel.Pipeline`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Pipeline) · [`obsdb.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#DB) · [`sqlite.Open`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb/sqlite#Open) · [`studio.Handler`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Handler) · [`studio.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#DB) · [`weft.TracerProvider`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#TracerProvider) · [`weft.LoggerProvider`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#LoggerProvider) · [`ExampleInstall`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#example-Install)
