Skip to content

Bridge your app's slog lines into runs

View as Markdown

otel.Slog() bridges slog.Default into weft’s pipeline: every line logged with a context that carries a span becomes an app log record under that span, beside the run’s own records. A tool handler’s slog.InfoContext(ctx, …) then shows on that tool call in Studio. The lines still go wherever they went before.

Bridge slog.Default and log from a tool handler, in applogs/main.go:

applogs/main.go
defer otel.Install(otel.Local(""), otel.Slog())() // slog.Default now tees to the pipeline
lookup := weft.Tool("lookup_order", "Look up an order by ID.",
func(ctx context.Context, in LookupInput) (string, error) {
slog.InfoContext(ctx, "looking up order", "order_id", in.OrderID) // ctx carries the call's span
slog.WarnContext(ctx, "order not in cache", slog.Group("cache", "region", "eu-1", "hit", false))
return "", &weft.ToolError{Code: "ORDER_NOT_FOUND", Message: "order " + in.OrderID + " does not exist"}
})

applogs/main.go on GitHub

The ctx a tool handler receives carries its execute_tool span, so both lines land on that tool call. A line logged with a context that has no span, outside any run, stays with your handler alone.

otel.Slog() is an Install option. Once the pipeline is registered, it wraps the default logger’s handler, so every slog.Default line logged under a span reaches the pipeline as well as its old handler: your own, those of weft.Logger (whose default is slog.Default), mw.Log(nil) and mw.Audit(slog.Default()). Shutdown restores the previous default. The package example ExampleSlog installs it and reads weft’s run lines back as the run’s app logs.

Each line becomes one record:

FieldValue
spanthe context’s span (table below)
scopegithub.com/weftgo/weft/otel/slog
severitythe slog level + 9, held to 1–24: DEBUG 5, INFO 9, WARN 13, ERROR 17; the level’s name as severity text
bodythe slog message
attributesflattened, a group’s keys joined with . (cache.region); durations and times as strings; a key starting weft. renamed slog.weft.…; the first 120 kept and the rest counted in weft.log.attrs_dropped

Which span a line lands on is the context it was logged with:

SpanLines
invoke_agentweft.Logger’s run start, run finish and, for a failed run in its place, run error
chatweft.Logger’s model call and model attempt; mw.Log’s lines; anything the model chain logs
execute_toolweft.Logger’s tool call; mw.Audit’s lines; a tool handler’s own lines

The bridge has no level of its own: every level, DEBUG included, goes to the pipeline, while the handler you had keeps filtering at its level. That is why the example’s DEBUG lines from weft.Logger are recorded although the terminal shows INFO and above. Lines from the pipeline itself, its WARNs about destinations, are never bridged.

A program that never called slog.SetDefault is on slog’s built-in handler, which cannot be wrapped. Its lines keep going to the log package’s writer through a slog.TextHandler at the level slog.SetLogLoggerLevel set (INFO unless changed, read once at Install), so their format changes to time=… level=… msg=… while the bridge is installed; shutdown puts the old form back. One Slog pipeline at a time: a second Install(…, otel.Slog()) wraps the first’s bridge. Shut them down in reverse order; out of order, the last shutdown still restores what the first found.

otel.SlogHandler(next) returns a handler that tees each record to next (when next is non-nil and enables the level) and to the installed pipeline, looked up per record. Build slog.New(otel.SlogHandler(h)) before or after Install: it starts teeing once Install has run and stops after shutdown. Pass that logger to weft.Logger, mw.Log or mw.Audit to route weft’s own lines through it. ExampleSlogHandler builds one before Install and stores a tool handler’s WARN under its execute_tool span.

Under otel.NoGlobal() nothing is installed, and otel.Slog() leaves slog.Default alone. Bind a handler to the pipeline with p.SlogHandler(next) instead, as a test in applogs/main_test.go does:

applogs/main_test.go
p, err := otel.Start(ctx, otel.NoEnv(), otel.NoGlobal(),
otel.Local(path), // takes app logs: content on
otel.Exporters(nil, vendor, otel.AppLogs(true)), // opted in: receives them stripped
otel.Exporters(nil, other), // not opted in: receives none
)
if err != nil {
t.Fatal(err)
}
logger := slog.New(p.SlogHandler(slog.DiscardHandler)) // tee to this pipeline, and to next
lookup := weft.Tool("lookup_order", "Look up an order by ID.",
func(ctx context.Context, in LookupInput) (string, error) {
logger.WarnContext(ctx, "slow lookup", "order_id", in.OrderID, "weft.run.id", "spoofed")
return "shipped", nil
})
agt := weft.New(script(), lookup,
weft.Logger(logger), // weft's own Debug run lines through the same bridge
weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider()))

applogs/main_test.go on GitHub

An app may log anything, prompts included, so app log lines are content. otel.AppLogs(on) decides per destination; by default Local and Studio with content on take them, and Datadog, Langfuse, OTLP and Exporters do not. AppLogs(true) admits the lines and never bypasses the destination’s content policy:

  • A content-on destination applies its Redact to the message and every string attribute, with the kind otel.ContentLog ("log"), then its MaxBytes cap (32 KiB by default), and sums what it cut in weft.content.truncated_bytes. A Redact that panics drops the line. ExampleContentLog masks a card number this way.
  • A content-off destination that opted in receives each line stripped: message and string values empty, weft.content stripped, time, severity, span and other attributes kept. In the test above, vendor receives the lines that way and other receives none.

AppLogs(false) keeps the lines from a Local or Studio destination. Under a full queue, bridged lines are shed with the deltas, before weft’s own records (queues). Records your app emits through the OTel Logs API itself are not the bridge’s, and AppLogs does not govern them.

An agent built with weft.Content(false) keeps content out of its own lines before any destination sees them: weft.Logger’s tool call line logs an error result’s size (err_bytes) instead of its text, and mw.Audit logs err_bytes and the ToolError code instead of the error and its cause. The switch is per agent: a weft.Subagent child built without Content(false) logs the error text and cause again, so build every agent in the delegation with it.

While a bridge is live, each run’s invoke_agent span carries weft.logs.bridged, the number of lines the bridge had emitted, on the copy sent to each destination that takes app logs. The span carries the count as it stood when the run began; each heartbeat carries the count so far. The mark says “this store holds the run’s bridged lines”. When a run’s stored root span lacks it and no line is attributed to the run, Studio’s logs route reads that as “no weft slog bridge was recorded for this run” and names the fix, otel.Install(…, otel.Slog()) or slog.New(otel.SlogHandler(h)).

The run page’s logs view (?view=logs, key l) lists every line attributed to the run, in time order: its offset from the run’s start, severity, body and attributes. A severity filter, ?lsev=info|warn|error, keeps a level and above. Jump to span opens the run-tree row the line was logged under (?sel=t:<span id>&tab=logs), or its nearest drawn ancestor. A tree row that holds WARN or ERROR lines carries a tick, E1 W2, read at severity=warn when the run counts such lines, and its drawer has a Logs tab. When that read hit its 10,000-line cap the tick reads ≥E1 W2: the counts are floors, and its title says at least … and the first 10,000 WARN+ lines were read. The view reads 1,000 lines a page up to 10,000 and badges a longer list truncated; while the run runs it reads on every 5 seconds. The devtools panel’s step heads link to the same view.

A run page's logs view: seven lines under the run's spans, the app's own INFO "looking up order" and WARN "order not in cache" lines among weft's DEBUG run, model and tool lines, each with jump to spanA run page's logs view: seven lines under the run's spans, the app's own INFO "looking up order" and WARN "order not in cache" lines among weft's DEBUG run, model and tool lines, each with jump to span
This page's program in Studio's logs view: "looking up order" at INFO and "order not in cache" at WARN, with the cache.* attributes flattened.

The JSON API behind it is GET /api/runs/{id}/logs?from=&limit=&severity=, under the capability logs in /api/meta:

{"logs": [{"index": 2, "time": "…", "severity": "INFO", "severity_number": 9,
"body": "looking up order", "attrs": {"order_id": "5678"}, "span_id": "…"}],
"holes": []}
  • A row carries event_name when the line is an OpenTelemetry event: the OTLP record’s EventName when it has one; a plain line has none. The logs view also takes an older SDK’s event.name attribute, which stays in the row’s attrs. The logs view draws a GenAI event (gen_ai.<role>.message, gen_ai.choice) as that message, with its role, content, an assistant’s tool calls and a choice’s finish reason, and weft mcp’s logs tool answers the field too.
  • from is the first index; next_from continues a full page. limit defaults to 100, at most 1,000.
  • severity keeps a level and above: trace, debug, info, warn, error, fatal, or a number 1–24.
  • holes names what the page cannot show: not_recorded (the run stored no span to attribute lines through, or the bridge hint above), truncated (the run’s traces hold more than 10,000 log lines in its window, so later lines may be missing), gap (lines naming a span that is not stored). A running run’s page is partial instead: lines under spans still open appear once those spans end.
  • A line logged through the OTel Logs API on the pipeline’s provider is an app log too, attributed the same way.
  • A read-scoped panel token is refused the route, 403 with the hidden badge: the lines may carry prompts.

The run row carries delta_count beside them: the deltas the run streamed, counted and never stored.

The route reads obsdb.DB.OtherLogs, which your program can call on the local sink too. The example reads its lines back and names each one’s span:

applogs/main.go
db := otel.LocalDB()
page, err := db.OtherLogs(ctx, res.ID, obsdb.LogQuery{}) // what Studio's runs/{id}/logs serves
if err != nil {
return err
}
spans, err := db.RunSpans(ctx, res.ID)
if err != nil {
return err
}
name := map[string]string{}
for _, s := range spans {
name[s.SpanID] = s.Name
}
for _, l := range page.Logs {
fmt.Fprintf(w, "%-5s %-18s %s%s\n", obsdb.SeverityText(l.Severity), l.Body, name[l.SpanID], attrs(l.Attrs))
}

applogs/main.go on GitHub

applogs/main.go
// Command applogs runs the example of the guide "Bridge your app's slog
// lines into runs": go run ./applogs. The model is scripted with
// wefttest, so it runs offline; the run and its log lines are recorded
// to ./.weft/weft.db (or $WEFT_DB) and read back from it.
package main
import (
"context"
"fmt"
"io"
"log"
"log/slog"
"os"
"sort"
"strings"
"github.com/weftgo/weft"
"github.com/weftgo/weft/obsdb"
"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"`
}
// 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":"5678"}`}),
wefttest.Say("I could not find order 5678."),
)
}
func main() {
if err := run(context.Background(), os.Stdout); err != nil {
log.Fatal(err)
}
}
func run(ctx context.Context, w io.Writer) error {
defer otel.Install(otel.Local(""), otel.Slog())() // slog.Default now tees to the pipeline
lookup := weft.Tool("lookup_order", "Look up an order by ID.",
func(ctx context.Context, in LookupInput) (string, error) {
slog.InfoContext(ctx, "looking up order", "order_id", in.OrderID) // ctx carries the call's span
slog.WarnContext(ctx, "order not in cache", slog.Group("cache", "region", "eu-1", "hit", false))
return "", &weft.ToolError{Code: "ORDER_NOT_FOUND", Message: "order " + in.OrderID + " does not exist"}
})
agt := weft.New(script(), weft.Name("support-bot"), lookup)
res, err := agt.Generate(ctx, weft.Prompt("Where is order 5678?"))
if err != nil {
return err
}
slog.InfoContext(ctx, "outside any run") // no span on ctx: not bridged
db := otel.LocalDB()
page, err := db.OtherLogs(ctx, res.ID, obsdb.LogQuery{}) // what Studio's runs/{id}/logs serves
if err != nil {
return err
}
spans, err := db.RunSpans(ctx, res.ID)
if err != nil {
return err
}
name := map[string]string{}
for _, s := range spans {
name[s.SpanID] = s.Name
}
for _, l := range page.Logs {
fmt.Fprintf(w, "%-5s %-18s %s%s\n", obsdb.SeverityText(l.Severity), l.Body, name[l.SpanID], attrs(l.Attrs))
}
return nil
}
// attrs prints the app's own attributes of a line, sorted.
func attrs(m map[string]any) string {
var keys []string
for k := range m {
if k == "order_id" || strings.HasPrefix(k, "cache.") {
keys = append(keys, k)
}
}
sort.Strings(keys)
var b strings.Builder
for _, k := range keys {
fmt.Fprintf(&b, " %s=%v", k, m[k])
}
return b.String()
}

View applogs/main.go on GitHub

From docs-site/examples:

Terminal window
go run ./applogs
go test ./applogs

Standard output, the lines read back from the local sink:

DEBUG run start invoke_agent support-bot
DEBUG model call chat script
INFO looking up order execute_tool lookup_order order_id=5678
WARN order not in cache execute_tool lookup_order cache.hit=false cache.region=eu-1
DEBUG tool call execute_tool lookup_order
DEBUG model call chat script
DEBUG run finish invoke_agent support-bot

On standard error the built-in handler, now a TextHandler, prints the INFO and WARN lines and outside any run; that last line had no span and is not in the database. TestPipelineSlogHandler checks the WARN’s severity (13), the weft.run.id key renamed slog.weft.run.id, the bridge mark on the root span and the stripped copy; TestAttributeCap logs 130 attributes and reads weft.log.attrs_dropped 10.

  • Log with the context you were given. Only a line logged with a span-carrying context is bridged; slog.Info without a context, or with context.Background(), names no run. (Source: otel.SlogHandler godoc)
  • Expect DEBUG lines in the store. The bridge sends every level; weft’s run lines are DEBUG. Filter in Studio with lsev=, not at the bridge. (Source: record contract §4, app log records)
  • Opt a third party in deliberately. AppLogs(true) on a content-off destination sends severity, span and non-string attributes only; on a content-on one it sends what you logged, after Redact. (Source: otel.AppLogs godoc; TestPipelineSlogHandler)
  • Shut bridged pipelines down in reverse order. Two Install(…, otel.Slog()) pipelines wrap each other; out of order, the last shutdown still restores what the first found. (Source: otel.Slog godoc)
  • Set Content(false) on every agent of a delegation. It governs only the agent it is passed to; a Subagent child without it logs err and cause text. (Source: CHANGELOG.md:283; core/content.go:32-45)
  • Use p.SlogHandler under NoGlobal. otel.Slog() and otel.SlogHandler follow the installed pipeline, and a NoGlobal pipeline is not installed. (Source: otel.Slog godoc)

Symbols used: otel.Slog · otel.SlogHandler · Pipeline.SlogHandler · otel.AppLogs · otel.ContentLog · otel.Install · otel.Start · otel.NoGlobal · otel.Exporters · weft.Logger · weft.Content · weft.ToolError · mw.Log · mw.Audit · obsdb.DB · ExampleSlog · ExampleSlogHandler · ExampleContentLog