Send records to Studio, Datadog, Langfuse or any OTLP backend
Pass each destination to otel.Install as an option; all of them are active at once. otel.Studio, otel.Datadog, otel.Langfuse, otel.OTLP and otel.Exporters each become their own processor chain with its own content policy, signals, batch queue and drop count, so a slow or failing destination never blocks the others. Content goes only to the local sink and Studio unless you turn it on for another destination.
Export every run to a Studio, in destinations/main.go:
return otel.Install( otel.Studio(studioURL, studioToken, // OTLP/HTTP, content on otel.QueueSize(1<<15)), // 32,768 records queued before it refuses (default 16,384))Destinations
Section titled “Destinations”| Destination | Sends to | Content | Signals | Queue |
|---|---|---|---|---|
otel.Local(path) | a SQLite file, written synchronously (Record every run) | on | traces, logs | none |
otel.Studio(url, token) | a Studio’s OTLP ingest, OTLP/HTTP protobuf, Authorization: Bearer <token> | on | traces, logs | 16,384 |
otel.Datadog() | the Datadog Agent’s OTLP intake, http://localhost:4318 | off | traces, logs | 2,048 |
otel.Langfuse(host, publicKey, secretKey) | <host>/api/public/otel/v1/traces, Basic auth | off | traces | 2,048 |
otel.OTLP(endpoint) | any OTLP/HTTP endpoint | off | traces, logs | 2,048 |
otel.Exporters(spans, logs) | your own sdktrace.SpanExporter and sdklog.Exporter, either nil | off | whichever is non-nil | 2,048 |
Every destination takes otel.DestOption values after its arguments:
| Option | Effect |
|---|---|
WithContent(cfg...) | content on, optionally with this destination’s own ContentConfig |
NoContent() | content off: bodies stripped, transcript records dropped |
Signals(traces, logs) | which signals this destination takes |
NoDeltas() | drops text, reasoning and argument deltas before export |
QueueSize(n) | the batch queue, records and spans each; n <= 0 keeps the default |
Blocking() | development only: a full queue waits for room instead of refusing |
BatchDelay(d) | the batch flush interval |
Headers(h) | extra HTTP headers (OTLP-family destinations) |
Timeout(d) | the export request timeout |
Insecure() | allows http:// to a host other than localhost, 127.0.0.1 and ::1 |
DatadogEndpoint(url) | the Datadog Agent’s intake URL |
AppLogs(on) | whether this destination takes bridged slog lines (app logs) |
The pipeline’s lifecycle covers every destination. Shutdown and ForceFlush flush them all in parallel under one budget, so a hung destination does not cost a healthy one its last records. Pipeline.Shutdown(ctx) stops the heartbeat goroutine, flushes (at most 5 seconds), shuts down the providers and closes the local databases last; its ctx bounds every one of those waits, the heartbeat’s included, so a stuck destination costs you the context and no more. It runs once: a concurrent or later call returns the first call’s result, or its own ctx’s error if that comes first. The function Install returns calls it with a 5-second context. A failed Start shuts down everything it built, exporters passed to Exporters included, and Install builds each destination once. A failed export is counted against its destination and named in a rate-limited WARN; records a content policy filters out are not counted as lost. The local sink keeps slice and map attributes as JSON arrays and objects, bytes as base64, and stores a structured body as JSON.
Studio
Section titled “Studio”otel.Studio(url, token) exports to a Studio over OTLP/HTTP protobuf, content on, with short batches: logs every 200 ms, spans every second. The URL’s path is kept, so a Studio mounted under /studio/ takes otel.Studio("https://app.example/studio", token) and receives POST /studio/v1/traces and /studio/v1/logs. The token travels as Authorization: Bearer, and the same token is what otel.StudioEndpoint() hands weft/runtime for the playground link. Studio checks the two against different options: ingest against studio.IngestToken, the API against studio.Token. Without an ingest token, ingest ignores the bearer and accepts loopback peers only. So one token serves both only when the Studio was built with studio.Token(tok) and studio.IngestToken(tok) set to the same value. weft studio sets no ingest token: it takes exports from this machine only, and an app on another host needs an embedded or hosted studio.New(…, studio.IngestToken(tok)).
Naming a Studio in code turns the discovery file off: the pipeline never joins a second Studio from it. WEFT_STUDIO_URL still adds its own, unless it points at the same URL: a code Studio and a different WEFT_STUDIO_URL both receive every record, and otel.StudioEndpoint() reports the environment’s one, the last built. Pass otel.NoEnv() to keep only yours. http:// to a Studio on a host other than localhost, 127.0.0.1 and ::1 is refused unless you pass Insecure(), because the destination carries a token.
Datadog
Section titled “Datadog”otel.Datadog() exports to the local Datadog Agent’s OTLP/HTTP intake, http://localhost:4318, content off, traces and logs. The Agent listens there when its OTLP receiver is enabled. otel.DatadogEndpoint(url) points it elsewhere. The spans carry the OTel GenAI attributes, which GenAI-aware backends read (the conventions weft writes).
Langfuse
Section titled “Langfuse”otel.Langfuse(host, publicKey, secretKey) exports traces to <host>/api/public/otel/v1/traces (any path in host is replaced), with Authorization: Basic base64(publicKey:secretKey), OTLP/HTTP only. Traces only: Langfuse ingests traces, and weft’s spans carry no content, so Langfuse gets timing, usage, tool names and the run’s identity, not prompts or results.
Any OTLP backend
Section titled “Any OTLP backend”otel.OTLP(endpoint) exports to any OTLP/HTTP endpoint (http(s)://host:port), content off, traces and logs, with the SDK’s batching. The endpoint’s path is kept as a prefix of /v1/traces and /v1/logs. A scheme-less endpoint is https://; any scheme but http and https fails the destination. http:// to a host other than localhost, 127.0.0.1 and ::1 needs Insecure(). Headers adds request headers, an API key for example, and Timeout sets the export timeout.
Four third-party destinations at once, each pointed at a stand-in on a loopback port:
p, err := otel.Start(ctx, otel.OTLP(collectorURL, // any OTLP/HTTP endpoint: content off otel.Headers(map[string]string{"X-Tenant": "acme"}), otel.Timeout(5*time.Second), otel.NoDeltas()), otel.Datadog(otel.DatadogEndpoint(agentURL)), // default http://localhost:4318: content off otel.Langfuse(langfuseURL, "pk-lf-demo", "sk-lf-demo"), // traces only otel.Exporters(nil, mine), // your own exporters, spans or logs or both: content off otel.NoEnv(), otel.NoGlobal(),)if err != nil { return err}agt := weft.New(script(), weft.Name("support-bot"), lookup, weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider()))res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))if err != nil { return err}if err := p.Shutdown(ctx); err != nil { return err}The collector receives every event with its content stripped, and no transcript record. The Datadog stand-in receives traces and logs; Langfuse receives traces only, with Basic auth.
Your own exporters
Section titled “Your own exporters”otel.Exporters(spans, logs) wires exporters you build: a vendor’s, stdout, a test’s in-memory one. Either may be nil; whichever is non-nil gets a chain, content off, with the SDK’s batching. BatchDelay and QueueSize apply to it like any other destination. To hand weft’s data to an SDK provider you already run instead, see Use your own OpenTelemetry SDK.
Signals and deltas
Section titled “Signals and deltas”otel.Signals(traces, logs) picks the signals a destination takes: spans (traces), records (logs), or both. The defaults are both, except Langfuse, traces only. A spans-only destination still sees every run’s structure; it holds no events and no transcript.
otel.NoDeltas() drops the text, reasoning and tool-argument deltas before export, for a destination that has no use for live streaming. No store keeps deltas by default (sqlite.KeepDeltas() and clickhouse.KeepDeltas() opt in), and they number on their own counter, so the durable event sequence keeps no hole.
Content per destination
Section titled “Content per destination”Content is message text, tool arguments and results, the system prompt and the catalog. A content-off destination receives every event with its shape kept and its content fields emptied, marked weft.content stripped, and no transcript, prompt or catalog record. otel.Content sets the redactor and the cap every content-on destination applies; WithContent(cfg) overrides it for one destination:
redact := func(kind weft.ContentKind, s string) string { return strings.ReplaceAll(s, "jane@example.com", "[email]") // every content field, every kind}p, err := otel.Start(ctx, otel.Local(path), // content on: the redactor and the cap apply otel.Content(otel.ContentConfig{MaxBytes: 32 << 10, Redact: redact}), otel.NoEnv(), otel.NoGlobal(),)ContentConfig’s Redact sees each content field before it leaves: event and delta bodies, transcript records part by part, prompt text, stop sequences and bridged log lines. It never changes what the model sees; a panic in it is contained, and the field goes out stripped or not at all. MaxBytes caps one event field or delta body, a prompt’s text and a catalog body (0 means 32 KiB, negative means no cap) and is never applied to transcript records. Control what content leaves the process covers the kinds, the cap and the agent-side switch, weft.Content.
Record provider wire bodies (development only)
Section titled “Record provider wire bodies (development only)”otel.RawBodies(true) records each model call attempt’s HTTP exchange, request and response as the first-party adapters sent and received them, as one weft.raw record per attempt. Studio shows it beside the step’s request. openai and anthropic capture through the SDK’s innermost per-request middleware, so every HTTP call is one pair, an SDK transport retry included, and a client you injected with Client(c) is captured too. google wraps the transport of the client it built itself: a genai.Client injected with google.Client(c) records no pair, and its requests read not_recorded (Connect a model provider).
p, err := otel.Start(ctx, otel.Local(filepath.Join(dir, "raw.db")), otel.RawBodies(true), // kept only under WEFT_ENV=dev; else one WARN and off otel.NoGlobal(),)if err != nil { return err}defer func() { _ = p.Shutdown(ctx) }()fmt.Fprintln(w, "raw bodies recorded:", p.LoggerProvider().RawBodies(), "WEFT_ENV="+os.Getenv("WEFT_ENV"))It takes effect only behind the development gate: WEFT_ENV=dev when the pipeline starts, or otel.DevMode() in code. Otherwise Start logs one WARN naming the cause, and the pipeline behaves as if the option were absent: LoggerProvider.RawBodies() answers false and the adapters buffer nothing. The WARN reads otel: RawBodies ignored: WEFT_ENV is not dev, or, under otel.NoEnv() without DevMode, otel: RawBodies ignored: otel.NoEnv reads no WEFT_ENV. Raw records go only to Local and Studio destinations with content on, never to Datadog, Langfuse, OTLP or Exporters. Each body is capped at 256 KiB; credential headers (Authorization, X-Api-Key, cookies, any *-key or *-token header) and credential query values are stripped before emission and listed in the record.
Open the gate in code with DevMode. otel.DevMode() is the code-side twin of WEFT_ENV=dev, for a test or harness that controls its own process, typically beside otel.NoEnv(), which reads no WEFT_ENV and so refuses all three development switches on its own. In destinations/main.go:
p, err := otel.Start(ctx, otel.NoEnv(), // reads no WEFT_ENV, WEFT_STUDIO_URL, OTEL_* or discovery file otel.DevMode(), // opens the development gate in code, and nothing else otel.Local(filepath.Join(dir, "dev.db")), otel.RawBodies(true), otel.NoGlobal(),)if err != nil { return err}defer func() { _ = p.Shutdown(ctx) }()fmt.Fprintln(w, "raw bodies recorded under DevMode:", p.LoggerProvider().RawBodies())DevMode satisfies the development gate, which RawBodies, a destination’s Blocking and otel.DevDetail need, and nothing else: no destination, discovery read or runtime link follows from it. The operator’s environment wins. When the pipeline reads the environment (no NoEnv) and WEFT_ENV is set to anything but dev, DevMode is refused with one WARN, otel: DevMode ignored: WEFT_ENV=<value>, and the switches stay off. Whenever DevMode is what opened the gate, Start logs one INFO line per switch it opened, such as otel: raw bodies on by otel.DevMode() and otel: Blocking on by otel.DevMode(), so a binary that ships it is visible. The package example ExampleDevMode shows it beside NoEnv.
Queue size and blocking
Section titled “Queue size and blocking”Every destination but Local holds its records and its spans in two separate batch queues between emission and export, each sized 16,384 for Studio and 2,048 for the others. otel.QueueSize(n) changes it. The OTEL_BLRP_MAX_QUEUE_SIZE and OTEL_BSP_MAX_QUEUE_SIZE variables do not apply to weft’s destinations.
A full queue never blocks the app. Each destination admits records ahead of the SDK’s queue and refuses them by tier:
| Queue fill | Refused |
|---|---|
| half full | deltas and bridged app log lines |
| seven eighths | ordinary records (events, transcript batches, requests) and spans other than a run’s root (chat, execute_tool, attempt) |
| full | run_start, run_finish, every run’s invoke_agent span (a subagent’s included), heartbeats |
Every refusal is counted. The destination logs one WARN, weft/otel: destination queue full, records dropped, naming itself and the knob. Once it has lost any record, it puts its running count, weft.records.dropped, on its copy of every heartbeat and of every later run’s run_start and run_finish records. Studio keeps the largest count heard from each service and shows it as ingest health (/api/meta’s ingest.dropped, the Settings page, weft doctor). The run itself says what it lost: its root span carries weft.run.events, and a store that holds fewer reads the gap badge, “N of M events were lost”. Local has no queue: it writes synchronously and loses nothing. The counts are safe under concurrent runs.
An export that fails loses its batch the same way, and nothing is resent. When a Studio or OTLP destination cannot be reached (Studio not running yet, a stale WEFT_STUDIO_URL, a wrong token), its records and spans are dropped once the exporter gives up: it retries only temporary failures (a 429 or 5xx, a timeout), so a refused connection or a 401 is dropped at once. The run is not affected, and the app sees only this WARN on slog.Default, at most once a minute per destination, with dest, the running dropped count and err, the export’s failure. Through a text handler:
level=WARN msg="weft/otel: destination dropped records" dest=studio dropped=8 err="Post \"http://127.0.0.1:1/v1/logs\": dial tcp 127.0.0.1:1: connect: connection refused"The loss is counted into weft.records.dropped, so once Studio hears the destination again, weft doctor’s ingest line names it (weft doctor). The runs exported while it was unreachable never reach that Studio. Add otel.Local beside it for a durable copy: the local sink writes synchronously, in-process.
otel.Blocking() makes a full queue wait for room instead of refusing a durable record: up to 5 seconds, never past the emitting run’s context, with deltas still shed. Once one wait times out, the destination refuses at once until an export begins, so a hung exporter costs one 5-second wait, not one per record. That first timed-out wait logs one WARN for the destination’s lifetime, naming it (studio, datadog, langfuse, otlp or exporters; Local has no queue and never stalls):
weft/otel: destination studio: exporter stalled — records are refused until it recovers (Blocking)It says the exporter stopped, where the queue-full WARN says only that the queue filled: no export began for a whole wait. The refused records are counted into weft.records.dropped as any overflow is. The destination waits again as soon as an export begins, and a later stall logs nothing more.
Like RawBodies it is development only: outside the development gate (WEFT_ENV=dev, or otel.DevMode()), Start logs otel: Blocking ignored: WEFT_ENV is not dev (under NoEnv, … otel.NoEnv reads no WEFT_ENV) and the destination refuses as without it. A Local destination’s Blocking is ignored silently: Local has no queue. In production, raise QueueSize.
otel.BatchDelay(d) sets how often a destination flushes its batch. Studio defaults to 200 ms for logs and 1 s for spans; the others use the SDK’s defaults. It applies to Exporters destinations too. The package examples ExampleQueueSize and ExampleBlocking show both options.
Environment
Section titled “Environment”The pipeline reads its environment for destinations as well as its options; Environment variables is the reference. In short:
WEFT_STUDIO_URL(withWEFT_STUDIO_TOKEN) adds a Studio, content on.http://to a host other thanlocalhost,127.0.0.1and::1is refused: writeotel.Studio(url, token, otel.Insecure())in code instead.OTEL_EXPORTER_OTLP_ENDPOINTadds an OTLP destination, content off unlessOTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=true;OTEL_EXPORTER_OTLP_HEADERSis percent-decoded. Anhttp://value is the operator’s opt-in for plaintext to that host,http://otel-collector:4318for example. It never downgrades anhttps://destination named in code, and a code-configuredotel.OTLP("http://…")to a host that is not loopback still needsInsecure().- With
WEFT_STUDIO_URLunset and nootel.Studioorotel.Localin code, the discovery file a runningweft studioorweft devwrote stands in for it. The pipeline looks in./.weft, then$XDG_RUNTIME_DIR/weft, then the user cache directory, and trusts a file only when its URL is loopback, it is under 24 hours old, its process is alive and, on Unix, it is mode 0600 and yours. It logs one INFO line,weft/otel: joined the running Studio.WEFT_DISCOVERY=off, orotel.NoDiscovery()in code, stops the read and nothing else (The discovery file). - The discovery file is read only when neither
otel.Studioorotel.Localin code norWEFT_STUDIO_URLnames a store. Anotel.OTLP,Datadog,LangfuseorExportersdestination does not switch it off. Code and the environment do not compete: a code Studio and a differentWEFT_STUDIO_URLboth receive the records, andotel.StudioEndpoint()reports the environment’s. Useotel.NoEnv()to keep only yours.
Explicit and environment destinations combine. An environment destination at the same resolved URL as an explicit one is dropped; the explicit one wins. otel.NoEnv() turns every environment destination and the discovery file off.
A zero-option otel.Install() with an environment destination exports there instead of writing the local sink. When no destination option was passed and every environment destination fails to build, Install falls back to the local sink with one WARN rather than recording nothing; a program that named its own destinations never gets one it did not name.
Complete example
Section titled “Complete example”// Command destinations runs the examples of the guide "Send records to// Studio, Datadog, Langfuse or any OTLP backend": go run ./destinations.// Every destination is a stand-in on a loopback port — a Studio, a// collector, a Datadog Agent, a Langfuse — so it runs offline, and the// model is scripted with wefttest.package main
import ( "context" "encoding/json" "fmt" "io" "log" "net/http" "net/http/httptest" "os" "path/filepath" "sort" "strings" "sync" "time"
"go.opentelemetry.io/otel/attribute" sdklog "go.opentelemetry.io/otel/sdk/log"
"github.com/weftgo/weft" "github.com/weftgo/weft/obsdb" "github.com/weftgo/weft/obsdb/sqlite" "github.com/weftgo/weft/otel" "github.com/weftgo/weft/studio" "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 to jane@example.com", 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() { dir, err := os.MkdirTemp("", "weft-destinations-") if err != nil { log.Fatal(err) } defer func() { _ = os.RemoveAll(dir) }() if err := run(context.Background(), os.Stdout, dir); err != nil { log.Fatal(err) }}
func run(ctx context.Context, w io.Writer, dir string) error { fmt.Fprintln(w, "== studio") if err := toStudio(ctx, w, dir); err != nil { return err } fmt.Fprintln(w, "== third parties") if err := toThirdParties(ctx, w, dir); err != nil { return err } fmt.Fprintln(w, "== content") if err := withContent(ctx, w, dir); err != nil { return err } fmt.Fprintln(w, "== raw bodies") if err := rawBodies(ctx, w, dir); err != nil { return err } return devMode(ctx, w, dir)}
// toStudio exports every run to a Studio over OTLP/HTTP.func toStudio(ctx context.Context, w io.Writer, dir string) error { studioURL, studioToken, studioDB, stop, err := standInStudio(filepath.Join(dir, "studio.db")) if err != nil { return err } defer stop()
shutdown := func() func() { return otel.Install( otel.Studio(studioURL, studioToken, // OTLP/HTTP, content on otel.QueueSize(1<<15)), // 32,768 records queued before it refuses (default 16,384) ) }() 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 } shutdown() // flush: every queued record leaves before the program exits
rec, err := studioDB.Run(ctx, res.ID) if err != nil { return err } fmt.Fprintln(w, "studio:", rec.Agent, rec.Status, "events:", rec.EventCount, "transcript batches:", rec.MessageCount) return nil}
// toThirdParties exports one run to an OTLP collector, a Datadog Agent,// Langfuse and the app's own exporter at once.func toThirdParties(ctx context.Context, w io.Writer, dir string) error { collectorURL, _, collectorDB, stopCollector, err := standInStudio(filepath.Join(dir, "collector.db")) if err != nil { return err } defer stopCollector() agent, langfuse := &receiver{}, &receiver{} agentSrv, langfuseSrv := httptest.NewServer(agent), httptest.NewServer(langfuse) defer agentSrv.Close() defer langfuseSrv.Close() agentURL, langfuseURL := agentSrv.URL, langfuseSrv.URL mine := &records{}
p, err := otel.Start(ctx, otel.OTLP(collectorURL, // any OTLP/HTTP endpoint: content off otel.Headers(map[string]string{"X-Tenant": "acme"}), otel.Timeout(5*time.Second), otel.NoDeltas()), otel.Datadog(otel.DatadogEndpoint(agentURL)), // default http://localhost:4318: content off otel.Langfuse(langfuseURL, "pk-lf-demo", "sk-lf-demo"), // traces only otel.Exporters(nil, mine), // your own exporters, spans or logs or both: content off otel.NoEnv(), otel.NoGlobal(), ) if err != nil { return err } agt := weft.New(script(), weft.Name("support-bot"), lookup, weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider())) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err } if err := p.Shutdown(ctx); err != nil { return err }
rec, err := collectorDB.Run(ctx, res.ID) if err != nil { return err } page, err := collectorDB.Events(ctx, res.ID, -1, 50) if err != nil { return err } stripped := 0 for _, e := range page.Events { if e.Content == "stripped" { stripped++ } } fmt.Fprintln(w, "collector:", rec.Status, "events:", rec.EventCount, "stripped:", stripped, "transcript batches:", rec.MessageCount) fmt.Fprintln(w, "datadog agent:", agent.paths()) fmt.Fprintln(w, "langfuse:", langfuse.paths(), "auth:", langfuse.authScheme()) fmt.Fprintln(w, "own exporter: records arrive", mine.contents()) return nil}
// withContent keeps content on for one destination and passes it// through a redactor and a cap first.func withContent(ctx context.Context, w io.Writer, dir string) error { path := filepath.Join(dir, "redacted.db") redact := func(kind weft.ContentKind, s string) string { return strings.ReplaceAll(s, "jane@example.com", "[email]") // every content field, every kind } p, err := otel.Start(ctx, otel.Local(path), // content on: the redactor and the cap apply otel.Content(otel.ContentConfig{MaxBytes: 32 << 10, Redact: redact}), otel.NoEnv(), otel.NoGlobal(), ) if err != nil { return err } agt := weft.New(script(), weft.Name("support-bot"), lookup, weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider())) res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err } if err := p.Shutdown(ctx); err != nil { return err } db, err := sqlite.Open(path) if err != nil { return err } defer func() { _ = db.Close() }() batches, err := db.Transcript(ctx, res.ID) if err != nil { return err } all := string(joinRaw(batches)) fmt.Fprintln(w, "the model saw:", toolResult(res)) fmt.Fprintln(w, "the sink holds [email]:", strings.Contains(all, "[email]"), "the address:", strings.Contains(all, "jane@example.com")) return nil}
// rawBodies shows the development switch refused outside WEFT_ENV=dev.func rawBodies(ctx context.Context, w io.Writer, dir string) error { p, err := otel.Start(ctx, otel.Local(filepath.Join(dir, "raw.db")), otel.RawBodies(true), // kept only under WEFT_ENV=dev; else one WARN and off otel.NoGlobal(), ) if err != nil { return err } defer func() { _ = p.Shutdown(ctx) }() fmt.Fprintln(w, "raw bodies recorded:", p.LoggerProvider().RawBodies(), "WEFT_ENV="+os.Getenv("WEFT_ENV")) return nil}
// devMode opens the development gate in code: under NoEnv the pipeline// reads no WEFT_ENV, and DevMode is its code-side twin.func devMode(ctx context.Context, w io.Writer, dir string) error { p, err := otel.Start(ctx, otel.NoEnv(), // reads no WEFT_ENV, WEFT_STUDIO_URL, OTEL_* or discovery file otel.DevMode(), // opens the development gate in code, and nothing else otel.Local(filepath.Join(dir, "dev.db")), otel.RawBodies(true), otel.NoGlobal(), ) if err != nil { return err } defer func() { _ = p.Shutdown(ctx) }() fmt.Fprintln(w, "raw bodies recorded under DevMode:", p.LoggerProvider().RawBodies()) return nil}
// standInStudio serves a Studio over a fresh SQLite file on a loopback// port: its OTLP ingest (/v1/traces, /v1/logs) takes loopback peers// without an ingest token.func standInStudio(path string) (url, token string, db obsdb.DB, stop func(), err error) { db, err = sqlite.Open(path) if err != nil { return "", "", nil, nil, err } token = "dev-token" srv := studio.New(studio.DB(db), studio.Token(token)) ts := httptest.NewServer(srv.Handler()) return ts.URL, token, db, func() { ts.Close(); _ = srv.Close(); _ = db.Close() }, nil}
// receiver is an OTLP/HTTP endpoint that remembers the paths and the// Authorization scheme of what it was sent, and answers 200.type receiver struct { mu sync.Mutex seen map[string]bool auth string}
func (r *receiver) ServeHTTP(w http.ResponseWriter, req *http.Request) { _, _ = io.Copy(io.Discard, req.Body) r.mu.Lock() if r.seen == nil { r.seen = map[string]bool{} } r.seen[req.URL.Path] = true r.auth, _, _ = strings.Cut(req.Header.Get("Authorization"), " ") r.mu.Unlock() w.Header().Set("Content-Type", "application/x-protobuf")}
func (r *receiver) paths() string { r.mu.Lock() defer r.mu.Unlock() var out []string for p := range r.seen { out = append(out, p) } sort.Strings(out) return strings.Join(out, " ")}
func (r *receiver) authScheme() string { r.mu.Lock() defer r.mu.Unlock() return r.auth}
// records is a log exporter that keeps the weft.content value of every// record it was handed.type records struct { mu sync.Mutex content map[string]bool}
func (r *records) Export(_ context.Context, recs []sdklog.Record) error { r.mu.Lock() defer r.mu.Unlock() if r.content == nil { r.content = map[string]bool{} } for _, rec := range recs { rec.WalkAttributes(func(kv attribute.KeyValue) bool { if kv.Key == "weft.content" { r.content[kv.Value.AsString()] = true } return true }) } return nil}
func (r *records) contents() string { r.mu.Lock() defer r.mu.Unlock() var out []string for c := range r.content { out = append(out, c) } sort.Strings(out) return strings.Join(out, " ")}
func (*records) Shutdown(context.Context) error { return nil }func (*records) ForceFlush(context.Context) error { return nil }
func joinRaw(batches []json.RawMessage) []byte { var out []byte for _, b := range batches { out = append(out, b...) } return out}
// toolResult is the text of the run's first tool result: what the model// read, never changed by a destination's redactor.func toolResult(res *weft.RunResult) string { for _, m := range res.Messages { for _, part := range m.Content { if r, ok := part.(weft.ToolResultPart); ok { return r.Content } } } return ""}From docs-site/examples:
go run ./destinationsgo test ./destinations== studiostudio: support-bot succeeded events: 8 transcript batches: 4== third partiescollector: succeeded events: 8 stripped: 8 transcript batches: 0datadog agent: /v1/logs /v1/traceslangfuse: /api/public/otel/v1/traces auth: Basicown exporter: records arrive stripped== contentthe model saw: order 1234 has shipped to jane@example.comthe sink holds [email]: true the address: false== raw bodiesraw bodies recorded: false WEFT_ENV=raw bodies recorded under DevMode: trueThe Studio holds the run with its transcript. The collector, a second Studio standing in for any OTLP backend, holds the same eight events stripped and no transcript. The redactor changed what the sink stored, not what the model read. Without WEFT_ENV=dev, RawBodies is off, and the WARN goes to stderr; under NoEnv with DevMode it is on, with its INFO line. TestPerDestinationContent turns content on for OTLP with WithContent() and off for Studio with NoContent(); TestRawBodiesUnderDev checks the WEFT_ENV=dev and NoEnv cases, TestDevMode the INFO line and WEFT_ENV=prod overruling DevMode, and TestRawBodiesRefusedUnderNoEnv the WARN that names NoEnv.
Best practices & gotchas
Section titled “Best practices & gotchas”- Keep content off third parties unless you mean it. Content is on only for Local and Studio by default;
WithContenton anOTLPorExportersdestination sends prompts and results there. (Source:otel/config.go:90-99; record contract §5) - Raise
QueueSize, notBlocking, in production.Blockingis refused outside the development gate (WEFT_ENV=devorotel.DevMode()); a refused record is counted and the run’s gap badge shows it. (Source:otel.Blockinggodoc;ExampleBlocking;TestBlockingRefusedOutsideDev) NoEnvalso refusesRawBodiesandBlocking, unlessDevModeis set. It stops readingWEFT_ENV, so aNoEnvpipeline records no raw bodies even underWEFT_ENV=dev; addotel.DevMode()in a test or harness that needs them. (Source:otel/pipeline.go:931-940devGate;TestRawBodiesUnderDev,TestDevMode)- Watch for the join line. A pipeline that names no Studio and no Local store in code, such as one whose only destinations are
OTLP,Datadog,LangfuseorExporters, or a zero-optionInstall(), still joins a runningweft studiothrough the discovery file, with one INFO line,weft/otel: joined the running Studio.otel.NoDiscovery(),WEFT_DISCOVERY=offorNoEnvkeeps it to what you named; an explicitLocalorStudiodoes too, since 0.19.0. (Source:otel/pipeline.go:224-236) - Give
Shutdowna context with room. Itsctxbounds the heartbeat stop, the flush and the provider shutdown; only the first call does the work, and a second call waits for it or for its ownctx. (Source:otel/pipeline.go:147-210) - Keep a
Localdestination when Studio may be down. A failed export is dropped and never resent; the only sign in the app isweft/otel: destination dropped records, once a minute. (Source:otel/proc.go:736-751, 787-812) - Expect no logs at Langfuse. It takes traces only, and spans carry no content. (Source:
otel.Langfusegodoc;otel/options.go:263-271)
See also
Section titled “See also”- Record every run with otel.Install
- Control what content leaves the process
- Run Studio: embedded, local binary or hosted
- Use your own OpenTelemetry SDK
- Environment variables
Symbols used: otel.Install · otel.Start · otel.Local · otel.Studio · otel.Datadog · otel.Langfuse · otel.OTLP · otel.Exporters · otel.DestOption · otel.Content · otel.ContentConfig · otel.RawBodies · otel.NoEnv · otel.NoGlobal · studio.IngestToken · weft.ContentKind