---
title: Use your own OpenTelemetry SDK
description: Send weft's spans and log records through a TracerProvider and LoggerProvider you already run, with weft.TracerProvider and weft.LoggerProvider or the OTel globals, and read which spans, attributes and records a run produces.
url: https://weftgo.dev/docs/observe/opentelemetry/
type: how-to
sources:
  - weft/AGENTS.md:90-92 (block 2, TracerProvider, LoggerProvider, Content)
  - weft/core/go.mod:5-9 (the OTel API, the Logs API, trace)
  - 'weft/core/agent.go:495-505 (TracerProvider), 940-947 (Agent.LoggerProvider), 949-955 (Agent.TracerProvider: the option''s value or the global resolved at New; thread''s summarizer spans), 957-963 (Agent.ContentCapture: set false without the option; thread''s session records)'
  - 'weft/core/records_test.go:520-531 (ExampleAgent_ContentCapture); weft commit 23ee085b (U12.1, first in core/v0.18.0: Agent.ContentCapture and Agent.TracerProvider with the thread record family); weft/CHANGELOG.md:224 (0.18.0: the session state log as OTel records, summarizer calls as chat spans)'
  - weft/core/content.go:32-45 (Content), 117-126 (LoggerProvider)
  - weft/facade.go:304 (weft.TracerProvider), 469 (weft.Content), 506 (weft.LoggerProvider)
  - weft/docs/adr/0016-observability.md:194-226 (O7 no content on spans; the default path costs no goroutine, lock or flush)
  - 'weft/docs/adr/0016-observability.md:290-294 (Recorded for later, not built: metrics, the gen_ai.client.* histograms)'
  - weft/docs/adr/0028-the-request-record.md:601-625 (a stock SDK provider never records raw bodies)
  - weft/docs/record-contract.md:46-76 (transport, resource, scope), 237-458 (spans), 486-537 (log records), 1629-1650 (GenAI conventions)
  - weft/core/observe.go:44 (instrumentationName github.com/weftgo/weft/core), 937-950 (tool error.type, ErrorType)
  - weft/otel/tracker.go:191-214 (heartbeats)
  - weft/otel/options.go:58-88 (Service, Resource, Sampler)
  - weft/otel/pipeline.go:788-828 (samplerOf, buildResource precedence)
  - weft/otel/fromsdk.go:24-31 (FromSDKSpans), 60-67 (FromSDKRecords)
  - weft/core/agent.go:698-710 (New resolves otel.GetTracerProvider and logglobal.GetLoggerProvider once, unless an option set them)
  - 'weft/otel/pipeline.go:842-847 (registerGlobals: Install only calls SetTracerProvider and SetLoggerProvider), 69 (Pipeline.TracerProvider), 73 (Pipeline.LoggerProvider), 218 (Start)'
  - 'go.opentelemetry.io/otel@v1.46.0/internal/global/state.go:70-91 and go.opentelemetry.io/otel/log@v0.22.0/internal/global/state.go:37-53 (the placeholder delegates once: delegateTraceOnce, delegateLoggerOnce)'
  - 'scratch proof (weft v0.17.0, docs a9 fix, in-memory span exporters): the app set its own global SDK, built before, ran otel.Install with an Exporters destination, built after; the app''s exporter got before''s 2 spans, the pipeline''s after''s only. Reinstall: early built before any Install and late after Install #1 went to #1; after its shutdown and Install #2 both ran again with nil errors and #2 got only fresh''s spans (built after #2). An agent built with weft.TracerProvider(p.TracerProvider()) and weft.LoggerProvider(p.LoggerProvider()) from otel.Start(NoGlobal) reported to p'
  - weft/core/allocheap_test.go:54-71 (TestWholeRunNoSDKAllocations, bound 160)
  - weft/core/otel_test.go:691 (ExampleTracerProvider); weft/core/records_test.go:536 (ExampleLoggerProvider)
  - weft/examples/otel/main.go, main_test.go, acceptance_test.go
  - weft/README.md:278-311 (Observability)
  - weft/CHANGELOG.md:2924, 4188, 4358, 4787, 4790, 4818, 4822, 4825, 6155, 6164, 6171, 6174, 6178
  - docs-site/examples/otelx/main.go, main_test.go TestOwnSDK, TestWithoutAnSDK, TestResourceAndSampling
---

# Use your own OpenTelemetry SDK

weft's core reports every run through the OpenTelemetry API, its one dependency. Register an SDK globally and every agent's spans and log records reach it with no weft option; or pass your providers to one agent with [`weft.TracerProvider`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#TracerProvider) and [`weft.LoggerProvider`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#LoggerProvider). Exporters and backends stay yours; `weft/otel` is one way to configure them, not a requirement.

Give an agent an SDK tracer provider and logger provider, in `otelx/main.go`:

```go title="otelx/main.go"
spans := tracetest.NewInMemoryExporter() // your exporter: OTLP, stdout, a vendor's
tp := sdktrace.NewTracerProvider(sdktrace.WithSyncer(spans))
defer func() { _ = tp.Shutdown(ctx) }()
records := &recordKinds{}
lp := sdklog.NewLoggerProvider(sdklog.WithProcessor(sdklog.NewSimpleProcessor(records)))
defer func() { _ = lp.Shutdown(ctx) }()

agt := weft.New(script(), weft.Name("support-bot"), lookup,
	weft.TracerProvider(tp), // spans: invoke_agent › chat, execute_tool
	weft.LoggerProvider(lp), // records: events, deltas, transcript batches
)
if _, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")); err != nil {
	return err
}
```

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

The in-memory exporters stand in for yours: an OTLP exporter, stdout, a vendor's.

## Tracer and logger providers

The core's only dependencies are the OTel trace API (`go.opentelemetry.io/otel` v1.46.0, with semconv v1.41.0) and the Logs API (`go.opentelemetry.io/otel/log` v0.22.0); the SDK, exporters and `weft/otel` live outside it.

`weft.TracerProvider(tp)` sets the provider the agent's runs report spans to. Without it, runs use the global tracer provider of `go.opentelemetry.io/otel`, a no-op until an SDK registers one. So a program that sets up an SDK globally gets weft's spans with no option, and a test or a program that injects its dependencies passes its own provider instead of touching the global.

`weft.LoggerProvider(lp)` does the same for records, through the OTel Logs API (`go.opentelemetry.io/otel/log`): the run's events, deltas, transcript batches and request records. Without it, runs use the Logs API's global provider. [`Agent.LoggerProvider()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.LoggerProvider) returns the provider an agent emits through, for code whose own records must land beside the run's: `weft/thread`'s compaction marker uses it. Two more accessors, since 0.18.0, serve the same code. [`Agent.TracerProvider()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.TracerProvider) returns the tracer provider the runs open their spans on, the option's value or the global resolved at `New`; `weft/thread` opens its summarizer's `chat` spans through it. [`Agent.ContentCapture()`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.ContentCapture) returns `(capture, set bool)`: `set` is false when no `weft.Content` option was given (content then follows the logger, as below), and `capture` is the option's value when it was. `weft/thread` asks it, so `Content(false)` keeps its session records' content out as it keeps the runs'. [`ExampleAgent_ContentCapture`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-Agent.ContentCapture) reads all three back.

**The globals are read once, at `weft.New`.** Before any SDK is set, the OTel API's global is a placeholder that forwards to the first provider ever set, and only that one. An SDK registered after `New` therefore reaches the agent only when it is the process's first global registration. An agent built after a provider was already set keeps that provider for good, whatever is set later.

**Content follows the provider's answer.** The core asks the logger's `Enabled` before it puts content into a record, unless the agent says otherwise with [`weft.Content`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Content): `Content(true)` always, `Content(false)` never. The SDK's simple and batch processors answer yes to every record, so a stock `sdklog.LoggerProvider` receives full content: transcript batches, request records, the catalog. `weft/otel`'s destinations answer per destination instead. To keep content out of your provider:

```go title="otelx/main.go"
quiet := weft.New(script(), weft.Name("support-bot"), lookup,
	weft.TracerProvider(tp), weft.LoggerProvider(lp),
	weft.Content(false), // no content in this agent's records, whatever the provider answers
)
```

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

Spans never carry content, whichever provider you use. A stock SDK provider also never receives raw provider bodies: those need `weft/otel`'s provider and [`otel.RawBodies`](https://weftgo.dev/docs/observe/destinations/#record-provider-wire-bodies-development-only).

To use `weft/otel`'s pipeline with your own exporters instead, pass them as a destination with `otel.Exporters` ([Your own exporters](https://weftgo.dev/docs/observe/destinations/#your-own-exporters)). `otel.Install` registers its providers globally, so agents built after it need no option. An agent built before it reaches the pipeline only when no SDK was set globally earlier in the process. Beside a global SDK of your own, start the pipeline with `otel.Start(ctx, otel.NoGlobal(), …)`, so it does not replace your SDK as the global, and pass `p.TracerProvider()` and `p.LoggerProvider()` from [`otel.Start`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Start) to the agent.

## Spans

Every run reports one span tree, children nested under their parents:

```text
invoke_agent support-bot          the run (Internal)
├─ chat <model>                   one model call: a step (Client)
│  └─ attempt                     one try, when the model chain reports attempts (Client)
├─ execute_tool lookup_order      one tool call (Internal)
│  └─ invoke_agent research       a Subagent child run, under its delegating call
└─ chat <model>
```

No span carries content: no prompt, message, tool argument or tool result, only ids, names, counts, durations, reasons and error types. Error text does travel: a failed run or model call records its error as the span's exception, with status `Error`. Every span carries `weft.run.id` and the run's [metadata](https://weftgo.dev/docs/guides/metadata/). `weft.version` on the run span and the resource is the framework's release, pinned by a test so it cannot go stale across a release.

| Span | Key attributes |
|---|---|
| `invoke_agent` | `gen_ai.agent.name`, `gen_ai.provider.name`, `gen_ai.request.model`, `weft.version`, `weft.instructions.hash`, `weft.manifest.hash`; for a child `weft.parent.run.id` and `weft.parent.call.id`; at the end the run's `gen_ai.usage.*` totals (subagents included), `weft.run.steps`, `weft.run.events`, `weft.run.messages`, `weft.run.stop_reason`, `weft.run.stopped_by`, `weft.cancel.cause`, `error.type` |
| `chat` | `weft.step.index`, `weft.stream`, the model asked; at the end the call's `gen_ai.usage.*`, `gen_ai.response.finish_reasons` (`stop`, `tool_calls`, `max_tokens`), `gen_ai.response.model`, `weft.model.tool_calls`, `weft.ttft_ms`, `error.type` |
| `attempt` | `weft.attempt.index` (from 1), `weft.attempt.layer` (`fallback` on `mw.Fallback`'s backup), `weft.attempt.wait_ms`, `weft.attempt.retry_after_ms`, `http.response.status_code`, `error.type` |
| `execute_tool` | `gen_ai.tool.name`, `gen_ai.tool.call.id`, `weft.step.index`, `weft.tool.seq`; `weft.tool.result_bytes`, `weft.tool.truncated_bytes`, `weft.tool.timeout_ms`, `weft.tool.queue_ms`, `weft.tool.pending`, `weft.tool.approved`, `weft.tool.denied`, `error.type` |

`error.type` on a run span is a closed table of snake_case tokens: `max_steps`, `usage_limit`, `loop_detected`, `model_retries_exceeded`, `model_contract`, `no_output`, `model_error` (a provider failure, the default) and others, plus `context.Canceled` and `context.DeadlineExceeded`. On a tool span it is the `ToolError` code when there is one (`INVALID_INPUT`, `NO_SUCH_TOOL`, `RETRY`, your own), else `timeout`, `panic`, the context error, the error's own `ErrorType()` string when an error in its chain declares one (`weft/mcp`'s `mcp_transport`, for example), or `tool_error`. A cancelled tool call reports `context.Canceled` like its run. [The record contract §3](https://github.com/weftgo/weft/blob/v0.20.2/docs/record-contract.md#3-spans) lists every attribute and when it is set.

Spans and slog lines are the loop's own reporting, not an observer: a [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap) sees the same events and receives the span-carrying context. [`ExampleTracerProvider`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-TracerProvider) prints a run's span tree.

## Log records

Every record is one OTel log record from the logger `github.com/weftgo/weft/core`, with an `EventName`, a JSON body, severity INFO (WARN for an errored `tool_finish`), and the attributes `weft.record` (its kind), `weft.run.id`, `gen_ai.agent.name`, `weft.content` and the run's metadata:

| `weft.record` | One per | Position |
|---|---|---|
| `event` | durable event, `run_start` to `run_finish` | `weft.event.pos` |
| `delta` | streamed text, reasoning or argument delta | `weft.delta.pos` |
| `messages` | transcript batch (content on only) | `weft.messages.index` |
| `request`, `prompt`, `tools` | model-call attempt; distinct system prompt; distinct catalog | their own `.index` |
| `raw` | HTTP exchange, `otel.RawBodies` in development only | `weft.raw.index` |
| `compaction` | `thread` session compaction, emitted by `weft/thread` | none: keyed on `weft.compaction.hash` |
| `heartbeat` | open run every 10 s, emitted by `weft/otel`'s pipeline only, never stored | none |

Each positioned kind's positions run from 0 per run. A record carries the trace and span ids of the context it was emitted on: event, delta and transcript records the `invoke_agent` span's, the model-call records the `chat` span's. Join records to spans on weft's ids (`weft.run.id`, `weft.step.index`, `gen_ai.tool.call.id`), not on span ids, which are zero without an SDK. [`ExampleLoggerProvider`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-LoggerProvider) prints a run's record sequence; [the record contract §4](https://github.com/weftgo/weft/blob/v0.20.2/docs/record-contract.md#4-log-records) gives every body.

## GenAI semantic conventions

weft writes the OTel GenAI conventions (semconv v1.41.0) beside its own keys, so a GenAI-aware backend renders its traces:

| Key | Where |
|---|---|
| `gen_ai.operation.name` | every span but `attempt`: `invoke_agent`, `chat`, `execute_tool` |
| `gen_ai.agent.name` | `invoke_agent`; every record |
| `gen_ai.provider.name`, `gen_ai.request.model` | `invoke_agent`, `chat`, `attempt` |
| `gen_ai.response.model` | `chat`, `attempt` on success; the `step_finish` record |
| `gen_ai.response.finish_reasons` | `chat` |
| `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens` | `invoke_agent` (run totals), `chat` (the call's) |
| `gen_ai.usage.cache_read.input_tokens`, `gen_ai.usage.cache_creation.input_tokens`, `gen_ai.usage.reasoning.output_tokens` | the same spans, when non-zero |
| `gen_ai.tool.name`, `gen_ai.tool.call.id` | `execute_tool`; `tool_start` and `tool_finish` records |
| `gen_ai.conversation.id` | every span and record of a run with a `weft.session.id`, and, under `weft/otel`'s pipeline, its heartbeats |
| `error.type` | failed spans |

weft never writes the conventions' opt-in content attributes, the input and output messages on spans: content travels in log records under each destination's content policy.

weft emits no OpenTelemetry metrics, only spans and log records. It never uses a `MeterProvider`, so the conventions' `gen_ai.client.token.usage` and `gen_ai.client.operation.duration` histograms are not produced, and a metrics pipeline wired to weft receives nothing. Token counts are on the spans instead: the `gen_ai.usage.*` attributes of `invoke_agent` and `chat` in the table above.

## Resource and sampling

When `weft/otel` builds the providers, three options shape them:

```go title="otelx/main_test.go"
p, err := otel.Start(ctx, otel.NoEnv(), otel.NoGlobal(),
	otel.Service("support-api"), // service.name; else OTEL_SERVICE_NAME, else the binary's name
	otel.Resource(sdkresource.NewSchemaless(attribute.String("deployment.environment.name", "staging"))),
	otel.Sampler(sdktrace.NeverSample()), // spans only: records are never sampled
	otel.Exporters(spanExp, sdklog.Exporter(multi{logExp, svc})),
)
```

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

- [`otel.Service(name)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Service) sets `service.name`; without it, `OTEL_SERVICE_NAME`, else the binary's name. Studio shows each run's service and filters traces by it.
- [`otel.Resource(r)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Resource) merges `r` over the detected resource. The order, lowest first: the binary's name and `weft.version`, then `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES`, then `Service`, then `Resource`.
- [`otel.Sampler(s)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Sampler) sets the trace sampler; the default is `ParentBased(AlwaysOn)`. It applies to spans only: records are log records and are never sampled, so a run sampled out of tracing still has its events and transcript. `TestResourceAndSampling` runs under `NeverSample`, gets no span, and still gets the run's records.

With your own SDK, set the resource and sampler on your providers as usual; weft adds nothing to them.

## Convert SDK data

[`otel.FromSDKSpans`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#FromSDKSpans) and [`otel.FromSDKRecords`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#FromSDKRecords) turn what an SDK exporter receives into `obsdb`'s model, value for value what Studio's OTLP ingest makes of the same data:

```go title="otelx/main.go"
converted := otel.FromSDKSpans(spans.GetSpans().Snapshots()) // obsdb.Span values, as OTLP ingest makes them
```

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

Use them in an exporter of your own that writes to an `obsdb.DB` (`db.Write(ctx, obsdb.Batch{Spans: …, Records: …})`), or to assert on spans in a test.

## Without an SDK

With no provider registered and no option, both providers are the API's no-ops: spans are non-recording, `Enabled` answers no, and nothing is marshalled for a record. A whole two-step run on this path stays under 160 allocations (128 measured), with no goroutine, lock or background flush. `TestWithoutAnSDK` runs the example's agent with no provider and gets the same answer.

## The otel example

The weft repository's [`examples/otel`](https://github.com/weftgo/weft/tree/v0.20.2/examples/otel) is its own module with the real SDK. A stdout exporter prints the span tree of a run that delegates to a subagent, and its test asserts the tree through the SDK's in-memory exporter. Its acceptance test checks that every record correlates to the run's trace, event positions are contiguous, and the transcript records rebuild the transcript byte for byte. All of it runs offline.

## Complete example

```go title="otelx/main.go"
// Command otelx runs the example of the guide "Use your own
// OpenTelemetry SDK": go run ./otelx. The agent reports to an SDK
// tracer provider and logger provider the program built itself, with
// in-memory exporters; the model is scripted with wefttest, so it runs
// offline.
package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"os"
	"sort"
	"strings"
	"sync"

	"go.opentelemetry.io/otel/attribute"
	sdklog "go.opentelemetry.io/otel/sdk/log"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	"go.opentelemetry.io/otel/sdk/trace/tracetest"

	"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)
	}
}

func run(ctx context.Context, w io.Writer) error {
	spans := tracetest.NewInMemoryExporter() // your exporter: OTLP, stdout, a vendor's
	tp := sdktrace.NewTracerProvider(sdktrace.WithSyncer(spans))
	defer func() { _ = tp.Shutdown(ctx) }()
	records := &recordKinds{}
	lp := sdklog.NewLoggerProvider(sdklog.WithProcessor(sdklog.NewSimpleProcessor(records)))
	defer func() { _ = lp.Shutdown(ctx) }()

	agt := weft.New(script(), weft.Name("support-bot"), lookup,
		weft.TracerProvider(tp), // spans: invoke_agent › chat, execute_tool
		weft.LoggerProvider(lp), // records: events, deltas, transcript batches
	)
	if _, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")); err != nil {
		return err
	}

	stubs := spans.GetSpans()
	sort.Slice(stubs, func(i, j int) bool { return stubs[i].StartTime.Before(stubs[j].StartTime) })
	byID := map[string]tracetest.SpanStub{}
	for _, s := range stubs {
		byID[s.SpanContext.SpanID().String()] = s
	}
	for _, s := range stubs {
		depth := 0
		for p := s.Parent; p.IsValid(); p = byID[p.SpanID().String()].Parent {
			depth++
		}
		fmt.Fprintf(w, "%s%s%s\n", strings.Repeat("  ", depth), s.Name, keyAttrs(s.Attributes))
	}
	fmt.Fprintln(w, "records:", records.summary())

	quiet := weft.New(script(), weft.Name("support-bot"), lookup,
		weft.TracerProvider(tp), weft.LoggerProvider(lp),
		weft.Content(false), // no content in this agent's records, whatever the provider answers
	)
	records.reset()
	if _, err := quiet.Generate(ctx, weft.Prompt("Where is order 1234?")); err != nil {
		return err
	}
	fmt.Fprintln(w, "records with Content(false):", records.summary())

	converted := otel.FromSDKSpans(spans.GetSpans().Snapshots()) // obsdb.Span values, as OTLP ingest makes them
	fmt.Fprintln(w, "converted spans:", len(converted)) // both runs: 4 spans each
	return nil
}

// keyAttrs prints the span attributes the page talks about, in a fixed
// order, for the spans that carry them.
func keyAttrs(kvs []attribute.KeyValue) string {
	want := []string{"gen_ai.operation.name", "weft.step.index", "gen_ai.tool.name",
		"gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens", "gen_ai.response.finish_reasons", "weft.run.stopped_by"}
	have := map[string]string{}
	for _, kv := range kvs {
		have[string(kv.Key)] = kv.Value.Emit()
	}
	var b strings.Builder
	for _, k := range want {
		if v, ok := have[k]; ok {
			fmt.Fprintf(&b, " %s=%s", strings.TrimPrefix(strings.TrimPrefix(k, "gen_ai."), "weft."), v)
		}
	}
	return b.String()
}

// recordKinds is a log exporter that counts records by weft.record kind
// and weft.content value.
type recordKinds struct {
	mu sync.Mutex
	n  map[string]int
}

func (r *recordKinds) Export(_ context.Context, recs []sdklog.Record) error {
	r.mu.Lock()
	defer r.mu.Unlock()
	if r.n == nil {
		r.n = map[string]int{}
	}
	for _, rec := range recs {
		kind, content := "", ""
		rec.WalkAttributes(func(kv attribute.KeyValue) bool {
			switch kv.Key {
			case "weft.record":
				kind = kv.Value.AsString()
			case "weft.content":
				content = kv.Value.AsString()
			}
			return true
		})
		r.n[kind+"("+content+")"]++
	}
	return nil
}

func (r *recordKinds) reset() {
	r.mu.Lock()
	defer r.mu.Unlock()
	r.n = nil
}

func (r *recordKinds) summary() string {
	r.mu.Lock()
	defer r.mu.Unlock()
	var out []string
	for k, v := range r.n {
		out = append(out, fmt.Sprintf("%s %d", k, v))
	}
	sort.Strings(out)
	return strings.Join(out, ", ")
}

func (*recordKinds) Shutdown(context.Context) error   { return nil }
func (*recordKinds) ForceFlush(context.Context) error { return nil }
```

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

From `docs-site/examples`:

```sh
go run ./otelx
go test ./otelx
```

```text
invoke_agent support-bot operation.name=invoke_agent usage.input_tokens=20 usage.output_tokens=10 run.stopped_by=final_answer
  chat script operation.name=chat step.index=0 usage.input_tokens=10 usage.output_tokens=5 response.finish_reasons=["tool_calls"]
  execute_tool lookup_order operation.name=execute_tool step.index=0 tool.name=lookup_order
  chat script operation.name=chat step.index=1 usage.input_tokens=10 usage.output_tokens=5 response.finish_reasons=["stop"]
records: delta(full) 1, event(full) 8, messages(full) 4, request(full) 2, tools(full) 1
records with Content(false): delta(none) 1, event(none) 8, request(stripped) 2
converted spans: 8
```

The stock logger provider received full content: four transcript batches, two request records and the catalog. With `weft.Content(false)` the same run sends no transcript or catalog record, its events and deltas marked `none` and its request records stripped.

## Best practices & gotchas

- **Decide content before you hand weft a stock provider.** Its processors answer yes to every record, so transcripts and tool results reach your exporter. Use `weft.Content(false)`, or `weft/otel` with a content-off destination. (Source: `weft.Content` godoc; `TestOwnSDK`)
- **Join on weft ids, not span ids.** Span ids are zero without an SDK and missing when sampled out; every record carries `weft.run.id`. (Source: record contract §1, §4)
- **Sampling never thins records.** A `Sampler` drops spans only; to send fewer records, use `otel.Signals` or `otel.NoDeltas` on a destination. (Source: `otel.Sampler` godoc; `TestResourceAndSampling`)
- **Do not wait for weft metrics.** There is no `MeterProvider` option and no `gen_ai.client.*` histogram; read token counts from the spans' `gen_ai.usage.*` attributes. (Source: `weft/docs/adr/0016-observability.md:290-294`)
- **Install the pipeline before you build agents, or pass its providers.** An agent binds to the global providers at `weft.New`. One built after your own global SDK, or after an earlier `otel.Install`, keeps reporting there: a later `Install` never reaches it. Once that earlier pipeline is shut down, its runs are recorded nowhere, with no error and no WARN. Call `otel.Install` once, at startup, before `weft.New`; otherwise build the agent with `weft.TracerProvider(p.TracerProvider())` and `weft.LoggerProvider(p.LoggerProvider())`, `p` from `otel.Start(ctx, otel.NoGlobal(), …)` when your own SDK stays the global. (Source: `weft/core/agent.go:698-710`, `weft/otel/pipeline.go:313-314, 842-847`; scratch proof in `sources`)
- **Pass providers explicitly in tests.** The globals are process-wide; `weft.TracerProvider` and `weft.LoggerProvider` keep a test's spans its own. (Source: `weft.TracerProvider` godoc)

## See also

- [Record every run with otel.Install](https://weftgo.dev/docs/observe/recording/): the pipeline that configures these providers for you
- [Send records to Studio, Datadog, Langfuse or any OTLP backend](https://weftgo.dev/docs/observe/destinations/)
- [Inspect agents written in other languages](https://weftgo.dev/docs/observe/other-languages/): the same conventions from a non-Go agent
- [The record contract](https://github.com/weftgo/weft/blob/v0.20.2/docs/record-contract.md)

Symbols used: [`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) · [`weft.Content`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Content) · [`Agent.LoggerProvider`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Agent.LoggerProvider) · [`weft.Tap`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tap) · [`otel.Service`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Service) · [`otel.Resource`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Resource) · [`otel.Sampler`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Sampler) · [`otel.FromSDKSpans`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#FromSDKSpans) · [`otel.FromSDKRecords`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#FromSDKRecords) · [`otel.Exporters`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Exporters) · [`otel.Start`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Start) · [`obsdb.Batch`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#Batch) · [`ExampleTracerProvider`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-TracerProvider) · [`ExampleLoggerProvider`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-LoggerProvider)
