otel

package
v0.24.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 31 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package otel wires weft's observability to one or more OpenTelemetry destinations at once — any OTLP endpoint, Datadog, Langfuse, your own exporters or a synchronous Sink — each with its own signals and content policy (ADR 0024, S2).

One Install, one set of spans and records, fanned out:

defer otel.Install(
    otel.OTLP("https://collector.internal:4318", otel.FirstParty()), // your own collector: content on
    otel.Datadog(),                                 // the local Datadog Agent's OTLP intake, content off
    otel.Langfuse("https://cloud.langfuse.com", pk, sk), // traces only
)()

The package reads the standard OpenTelemetry variables only (OTEL_EXPORTER_OTLP_ENDPOINT and _HEADERS, OTEL_SERVICE_NAME, OTEL_RESOURCE_ATTRIBUTES, the GenAI content-capture variable) plus WEFT_ENV for the development gate. With nothing configured Install records nothing and says so in one INFO line. A local viewer's store plugs in as a Sink (a synchronous, first-party destination) or as an OTLP destination marked FirstParty; weft itself knows no viewer.

The rules that shape it:

  • Content is captured once and shaped per destination [D2]. Every processor registered here answers the Logs API's Enabled by event name: the core asks of each pure-content kind ("weft.messages", and ADR 0028's "weft.prompt" and "weft.tools") and emits content when any destination wants it. Content-off chains clone the record first (the SDK hands every processor the same pointer), strip the body with core.StripContent, empty a request record's params.stop and drop messages, prompt and tools records; content-on chains redact and cap event and delta bodies and redact (never cap) the transcript records part by part. The core reads no environment variable — this module does, here only.
  • The run tracker keeps the set of open runs and emits one weft.heartbeat record per open run per interval, so a 45 s tool call reads running and a crashed process stops heartbeating (the "interrupted" rule stays honest). Sinks never store heartbeats.
  • The slog bridge (Slog wraps slog.Default; SlogHandler wraps any handler) tees every line logged on a span-carrying context to the pipeline as an app log record with that span's ids — weft.Logger's run lines, mw.Log's, the app's own — for the destinations AppLogs admits (first-party destinations with content on by default), each line shaped by the destination's content policy (Redact, MaxBytes; stripped when content is off). While it is live, heartbeats and each run's invoke_agent span carry weft.logs.bridged on the destinations that take the lines; a viewer reads its absence as "no weft slog bridge was recorded for this run".
  • A Sink is written synchronously: nothing emitted is lost before Emit returns — within the destination's Timeout (default 2 s): a Sink that hangs is abandoned and its records counted dropped, never a stalled run (telemetry never blocks control).
  • Loss is said: Pipeline.Shutdown returns a *LossError matching ErrRecordsLost when any record was lost, beside the flush's and the providers' errors, and Install's function logs it.
  • Install never panics and never fails the program; Start returns errors and leaves the globals alone under NoGlobal (tests).

This module depends on the OTel SDK and the OTLP/HTTP exporters; the core never does. It never imports weft/thread, and nothing of a platform (a store, a viewer): those import otel, never the reverse.

Index

Examples

Constants

View Source
const ContentLog core.ContentKind = "log"

ContentLog is the kind the destination's Redact receives for a bridged app log line (Slog, SlogHandler): its message and each of its string attributes. It is not a core kind — the core never logs content into a record; the bridge carries what the app logged.

View Source
const ContentThread core.ContentKind = "thread"

ContentThread is the kind Redact sees for a weft/thread session record's content fields (record contract §4, kind thread): who decided, a deny reason, resolved content, a grant's reason, a queued or steered message's text, a branch summary, a delegated task and its answer — each string under the body's "content" object. A content-off destination receives none of them (the object is removed, weft.content = stripped); the record's ids, enums, counts and app-chosen names (a label's name) ride either way.

Variables

View Source
var ErrNoDestinations = errors.New("otel: no destinations configured")

ErrNoDestinations is Start's answer when nothing is configured: no destination option, no environment destination and no Fallback. Install answers it with one INFO line and a no-op.

View Source
var ErrRecordsLost = errors.New("otel: records lost")

ErrRecordsLost is what Pipeline.Shutdown's error matches when any record was lost during the pipeline's life: errors.Is(err, otel.ErrRecordsLost); errors.As a *LossError for the counts.

Functions

func Install

func Install(opts ...Option) func()

Install starts the pipeline and registers it globally. It never panics and never fails the program: a destination that cannot be built is logged (slog, WARN) and skipped. With nothing configured — no destination option, no OTEL_EXPORTER_OTLP_ENDPOINT, no Fallback — it records nothing: one INFO line says how to configure a destination, and the returned function is a no-op. When no destination option was passed and every environment destination failed to build, it uses the Fallback destinations with one WARN, if there are any; a program that passed its own destinations gets no destination it did not name. The returned function flushes and shuts everything down; call it on exit.

Example

Install is the whole setup: it registers the OTel globals the core reads, never fails the program, and returns the shutdown to call on exit. NoEnv keeps the example hermetic — no OTEL_* variable can add a destination behind it. FirstParty marks the exporters as the operator's own: content on.

package main

import (
	"context"
	"fmt"
	"log"
	"strings"
	"sync"

	"github.com/weftbase/weft"
	"github.com/weftbase/weft/otel"
	"github.com/weftbase/weft/wefttest"
	"go.opentelemetry.io/otel/attribute"

	sdklog "go.opentelemetry.io/otel/sdk/log"
)

// memLogs is an in-memory log exporter: the examples' stand-in for a
// store or a collector.
type memLogs struct {
	mu   sync.Mutex
	recs []sdklog.Record
}

func (m *memLogs) Export(_ context.Context, recs []sdklog.Record) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	for _, r := range recs {
		m.recs = append(m.recs, r.Clone())
	}
	return nil
}

func (m *memLogs) Shutdown(context.Context) error   { return nil }
func (m *memLogs) ForceFlush(context.Context) error { return nil }

// attr reads one string attribute off a record.
func attr(r sdklog.Record, key string) string {
	var out string
	r.WalkAttributes(func(kv attribute.KeyValue) bool {
		if string(kv.Key) == key {
			out = kv.Value.String()
			return false
		}
		return true
	})
	return out
}

// appLogs is the records the slog bridge teed: they carry no weft
// record kind.
func (m *memLogs) appLogs() []sdklog.Record {
	m.mu.Lock()
	defer m.mu.Unlock()
	var out []sdklog.Record
	for _, r := range m.recs {
		if attr(r, "weft.record") == "" && r.EventName() == "" {
			out = append(out, r)
		}
	}
	return out
}

func main() {
	logs := &memLogs{}
	shutdown := otel.Install(
		otel.NoEnv(),
		otel.Exporters(nil, logs, otel.FirstParty()),
	)

	// A scripted run through the installed globals — a real program
	// wires nothing: the core reads the providers Install registered.
	agt := weft.New(
		wefttest.Script(wefttest.Say("all done")),
		weft.Name("example"),
	)
	if _, err := agt.Generate(context.Background(), weft.Prompt("go"),
		weft.Metadata(map[string]string{"weft.session.id": "example-session"})); err != nil {
		log.Fatal(err)
	}
	shutdown() // flush every destination

	// The run's durable events, and the transcript the messages records
	// hold.
	var events []string
	messages := 0
	for _, r := range logs.recs {
		switch attr(r, "weft.record") {
		case "event":
			events = append(events, attr(r, "weft.event.type"))
		case "messages":
			messages += strings.Count(r.Body().AsString(), `"role"`)
		}
	}
	fmt.Println(strings.Join(events, " "), "·", messages, "messages")
}
Output:
run_start step_start step_finish run_finish · 2 messages

func SlogHandler

func SlogHandler(next slog.Handler) slog.Handler

SlogHandler returns a slog.Handler that tees every record to next (when next is non-nil and enables its level) and to the installed pipeline (Install, or Start without NoGlobal), looked up per record: built before Install, it starts teeing once Install has run, and stops after the pipeline's shutdown. Use it to bridge a logger the program builds itself — slog.New(otel.SlogHandler(h)) — or pass that logger to weft.Logger, mw.Log or mw.Audit; Slog does the same for slog.Default.

A bridged record is an app log record (record contract §5): the slog message as its body; the slog level as its severity (DEBUG 5, INFO 9, WARN 13, ERROR 17 — level + 9, held to 1–24) and severity text; the attributes flattened, a group's keys joined with "." (a key starting "weft." — "weft.run.id", "weft.record", which would make the record read as weft's own — is renamed "slog.weft.…"), the first 120 kept and the rest counted in weft.log.attrs_dropped; durations and times as their string forms; the trace and span ids of ctx. Only a line logged under a valid span context is teed — a line with no span names no run and stays with next alone — and only at a level some destination takes: the bridge itself has no level, every slog level (DEBUG included: weft's own lines are Debug) goes to the pipeline. Which destinations receive the lines is AppLogs': first-party destinations with content on by default, never a third party unless it opts in. Each destination shapes a line by its content policy (ContentConfig): Redact over the message and string attributes (ContentLog), each capped at MaxBytes with weft.content.truncated_bytes; a content-off destination that opted in gets the line stripped — severity, span and non-string attributes kept, message and string values emptied, weft.content "stripped". Under a full queue bridged lines are shed with the deltas, before weft's own records.

Example

SlogHandler bridges a logger the program builds itself: here a tool handler's WARN, logged with the tool call's context, is exported under that call's execute_tool span — the line and the step it came from, joined. The handler follows the installed pipeline, so it may be built before Install.

package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"log/slog"
	"sync"

	"github.com/weftbase/weft"
	"github.com/weftbase/weft/otel"
	"github.com/weftbase/weft/wefttest"
	"go.opentelemetry.io/otel/attribute"

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

// memLogs is an in-memory log exporter: the examples' stand-in for a
// store or a collector.
type memLogs struct {
	mu   sync.Mutex
	recs []sdklog.Record
}

func (m *memLogs) Export(_ context.Context, recs []sdklog.Record) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	for _, r := range recs {
		m.recs = append(m.recs, r.Clone())
	}
	return nil
}

func (m *memLogs) Shutdown(context.Context) error   { return nil }
func (m *memLogs) ForceFlush(context.Context) error { return nil }

// attr reads one string attribute off a record.
func attr(r sdklog.Record, key string) string {
	var out string
	r.WalkAttributes(func(kv attribute.KeyValue) bool {
		if string(kv.Key) == key {
			out = kv.Value.String()
			return false
		}
		return true
	})
	return out
}

// appLogs is the records the slog bridge teed: they carry no weft
// record kind.
func (m *memLogs) appLogs() []sdklog.Record {
	m.mu.Lock()
	defer m.mu.Unlock()
	var out []sdklog.Record
	for _, r := range m.recs {
		if attr(r, "weft.record") == "" && r.EventName() == "" {
			out = append(out, r)
		}
	}
	return out
}

func main() {
	logger := slog.New(otel.SlogHandler(slog.NewTextHandler(io.Discard, nil)))
	spans, logs := tracetest.NewInMemoryExporter(), &memLogs{}
	shutdown := otel.Install(otel.NoEnv(), otel.Exporters(spans, logs, otel.FirstParty()))

	lookup := weft.Tool("lookup", "Look an order up.", func(ctx context.Context, in struct {
		ID string `json:"id"`
	}) (string, error) {
		logger.WarnContext(ctx, "slow lookup", "id", in.ID)
		return "shipped", nil
	})
	agt := weft.New(wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{Name: "lookup", Args: `{"id":"42"}`}),
		wefttest.Say("shipped")), weft.Name("example"), lookup)
	if _, err := agt.Generate(context.Background(), weft.Prompt("where is 42?")); err != nil {
		log.Fatal(err)
	}
	// Flush before reading: the in-memory span exporter forgets its
	// spans at shutdown.
	if err := otel.Installed().ForceFlush(context.Background()); err != nil {
		log.Fatal(err)
	}
	names := map[string]string{}
	for _, s := range spans.GetSpans() {
		names[s.SpanContext.SpanID().String()] = s.Name
	}
	shutdown()
	for _, l := range logs.appLogs() {
		fmt.Println(l.Severity(), l.Body().AsString(), "·", names[l.SpanID().String()], "· id", attr(l, "id"))
	}
}
Output:
WARN slow lookup · execute_tool lookup · id 42

func TagOf

func TagOf(o Option) any

TagOf returns the tag of an option Tag built, else nil. It looks at o itself only, not inside an Options set.

Types

type ContentConfig

type ContentConfig struct {
	// MaxBytes caps one event field or delta body, a prompt record's
	// text and a tools record's body (whole tool entries dropped from
	// the end, so the body stays JSON); 0 = 32 KiB; negative =
	// unlimited. A cut sets weft.content.truncated_bytes. The default
	// applies to tools bodies too: a large catalog (an MCP server's, say)
	// arrives truncated, with truncated_bytes set — raise MaxBytes for
	// the local sink when the full catalog is wanted. Never applied to
	// messages records — a capped transcript is not replay-grade.
	MaxBytes int
	// Redact is applied to a content field before the cap; nil = identity.
	// It sees event and delta bodies and weft.messages transcript
	// records, the latter part by part with the kind the same content
	// has on the event path: text parts (every role) core.ContentText,
	// reasoning core.ContentReasoning, tool-call args core.ContentArgs (an
	// output that is not JSON is carried as a JSON string), tool results
	// core.ContentResult. It also sees a prompt record's text
	// (core.ContentPrompt) and each stop sequence of a request record
	// (core.ContentStop); a tools record is capped, never redacted (ADR
	// 0028 §6), and a bridged app log line's message and string
	// attributes (ContentLog; Slog, SlogHandler — capped too, a panic
	// drops the line). Ids, names, roles, signatures, file parts and hashes are
	// not passed to it; a transcript record is redacted, never capped. It
	// runs on the run's goroutine: a panic in it is contained — the event
	// goes out stripped, the transcript record not at all — and counted
	// as the destination's drop; so is a transcript record that cannot be
	// decoded for redaction. Nothing it was given is ever sent unredacted.
	Redact func(kind core.ContentKind, s string) string
}

ContentConfig carries the caps and redaction that live per destination, not in the core ([D2]: the core cannot discover them — the OTel global never hands out the SDK provider).

type DestOption

type DestOption interface {
	// contains filtered or unexported methods
}

DestOption configures one destination.

func AppLogs

func AppLogs(on bool) DestOption

AppLogs says whether this destination takes the slog bridge's app log records (Slog, SlogHandler): on by default for a first-party destination (FirstParty, Sink) with content on, off for the rest — and for a first-party destination under NoContent — because an app's log lines may carry anything it logged, prompts included. AppLogs(true) is the opt-in: it admits the lines, never bypasses the destination's content policy — an app log line is content like a transcript record, so a content-on destination applies ContentConfig's Redact (ContentLog) and MaxBytes to its message and string attributes, and a content-off one receives it stripped (message and string values emptied, weft.content=stripped; severity, span and the other attributes kept). AppLogs(false) keeps them from a first-party destination. Only a destination that takes the lines carries the bridge mark (weft.logs.bridged on its heartbeats and root spans). Records the app emits through the OTel Logs API itself are not the bridge's and are not governed by it.

func BatchDelay

func BatchDelay(d time.Duration) DestOption

BatchDelay sets the destination's batch flush interval, for logs and spans both (default: the SDK's).

func BatchDelays

func BatchDelays(logs, spans time.Duration) DestOption

BatchDelays sets the destination's log and span batch flush intervals apart (0 keeps the SDK's default for that signal) — a live viewer wants records sooner than spans.

func Blocking

func Blocking() DestOption

Blocking makes a full queue wait for room instead of refusing a durable record — up to 5 s and never past the emitting run's context (a span's End, which has none, waits under its own 5 s deadline); deltas are still shed. The bound is per stall: once a wait times out (the exporter is stuck), every later record is refused at once, counted, until an export begins again — a hung exporter costs the app one 5 s wait, not one per record. Development only, like RawBodies: it takes effect only when the pipeline starts under the dev gate (WEFT_ENV=dev read unless NoEnv, or DevMode — which an explicit WEFT_ENV other than dev overrules); otherwise Start logs one WARN naming the cause ("otel: Blocking ignored: WEFT_ENV is not dev", or "… otel.NoEnv reads no WEFT_ENV") and the destination refuses as without it — observability never slows a production app. A Sink ignores it (no queue).

Example

Blocking is development-only: under WEFT_ENV=dev (or DevMode) a full queue waits (up to 5 s) for room instead of refusing a durable record. Anywhere else — and under NoEnv without DevMode, as here — Start ignores it with one WARN naming the cause and the destination refuses as without it: observability never slows a production app. QueueSize is the production knob.

package main

import (
	"context"
	"log"
	"log/slog"
	"os"
	"sync"

	"go.opentelemetry.io/otel/attribute"
	sdklog "go.opentelemetry.io/otel/sdk/log"

	"github.com/weftbase/weft/otel"
)

func main() {
	prev := slog.Default()
	defer slog.SetDefault(prev)
	slog.SetDefault(slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey || a.Key == "hint" {
				return slog.Attr{}
			}
			return a
		},
	})))

	p, err := otel.Start(context.Background(),
		otel.NoEnv(), otel.NoGlobal(),
		otel.Exporters(nil, &eventNames{}, otel.Blocking()),
	)
	if err != nil {
		log.Fatal(err)
	}
	_ = p.Shutdown(context.Background())
}

// eventNames is a log exporter that remembers the weft.event.type of
// every record it exported.
type eventNames struct {
	mu    sync.Mutex
	types map[string]bool
}

func (e *eventNames) Export(_ context.Context, recs []sdklog.Record) error {
	e.mu.Lock()
	defer e.mu.Unlock()
	if e.types == nil {
		e.types = map[string]bool{}
	}
	for _, r := range recs {
		r.WalkAttributes(func(kv attribute.KeyValue) bool {
			if kv.Key == "weft.event.type" {
				e.types[kv.Value.AsString()] = true
			}
			return true
		})
	}
	return nil
}

func (e *eventNames) saw(typ string) bool {
	e.mu.Lock()
	defer e.mu.Unlock()
	return e.types[typ]
}

func (*eventNames) Shutdown(context.Context) error   { return nil }
func (*eventNames) ForceFlush(context.Context) error { return nil }
Output:
level=WARN msg="otel: Blocking ignored: otel.NoEnv reads no WEFT_ENV"

func DatadogEndpoint

func DatadogEndpoint(url string) DestOption

DatadogEndpoint overrides the Datadog destination's OTLP intake URL (default http://localhost:4318).

func FirstParty

func FirstParty() DestOption

FirstParty marks a destination as one the program's operator runs (a local store, an in-house viewer): content on by default (NoContent still turns it off), and eligible for RawBodies' raw records, DevDetail's layer spans and the slog bridge's app logs (AppLogs) — what never goes to a third party by default. Every Sink is first-party; on OTLP and Exporters it is the opt-in.

func Headers

func Headers(h map[string]string) DestOption

Headers adds HTTP headers to the destination's requests (OTLP-family destinations).

func Insecure

func Insecure() DestOption

Insecure allows http:// to a non-loopback host (OTLP-family destinations). Loopback http is always allowed, and so is the environment's OTEL_EXPORTER_OTLP_ENDPOINT written with http:// (the operator's opt-in; see envDestinations).

func Name

func Name(name string) DestOption

Name sets the destination's label in its WARN lines and drop counter (default: the kind's name — "otlp", "datadog", …).

func NoContent

func NoContent() DestOption

NoContent turns content off: the chain strips event and delta bodies (core.StripContent) and drops messages records before its exporter.

func NoDeltas

func NoDeltas() DestOption

NoDeltas drops text/reasoning/args deltas before export, to save bandwidth when live streaming is not wanted. Deltas are never stored by the sinks either way (Q4); the core's durable sequence is untouched (they number on their own counter, D3).

func QueueSize

func QueueSize(n int) DestOption

QueueSize sets how many records (and, separately, spans) the destination holds between emission and export — its batch queue (default the SDK's 2,048; n <= 0 keeps the default). A full queue never blocks the app: it refuses the record, deltas first (at half full), then ordinary records (at seven eighths), a run's run_start and run_finish last. Every refusal is counted: one WARN per destination ("weft/otel: destination queue full"), the count on the heartbeat and every run's run_start and run_finish (weft.records.dropped), and the run's gap, which a viewer counts against weft.run.events. A Sink has no queue (it writes synchronously) and ignores it. The OTEL_BLRP_MAX_QUEUE_SIZE and OTEL_BSP_MAX_QUEUE_SIZE variables do not apply to weft's destinations.

Example

QueueSize sizes one destination's batch queue — here a pair of the app's own exporters. A full queue never blocks the app: it refuses records (deltas first, run_start and run_finish last), counts them (weft.records.dropped on the heartbeat and the run brackets) and warns once ("weft/otel: destination queue full"), and the run's gap badge says what was lost. Raise it for a destination that falls behind under bursts.

package main

import (
	"context"
	"fmt"
	"log"
	"sync"

	"go.opentelemetry.io/otel/attribute"
	sdklog "go.opentelemetry.io/otel/sdk/log"

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

func main() {
	exp := &eventNames{}
	p, err := otel.Start(context.Background(),
		otel.NoEnv(), otel.NoGlobal(),
		otel.Exporters(nil, exp, otel.QueueSize(1<<15)),
	)
	if err != nil {
		log.Fatal(err)
	}
	agt := weft.New(wefttest.Script(wefttest.Say("done")),
		weft.LoggerProvider(p.LoggerProvider()))
	if _, err := agt.Generate(context.Background(), weft.Prompt("go")); err != nil {
		log.Fatal(err)
	}
	if err := p.Shutdown(context.Background()); err != nil {
		log.Fatal(err)
	}
	fmt.Println(exp.saw("run_start"), exp.saw("run_finish"))
}

// eventNames is a log exporter that remembers the weft.event.type of
// every record it exported.
type eventNames struct {
	mu    sync.Mutex
	types map[string]bool
}

func (e *eventNames) Export(_ context.Context, recs []sdklog.Record) error {
	e.mu.Lock()
	defer e.mu.Unlock()
	if e.types == nil {
		e.types = map[string]bool{}
	}
	for _, r := range recs {
		r.WalkAttributes(func(kv attribute.KeyValue) bool {
			if kv.Key == "weft.event.type" {
				e.types[kv.Value.AsString()] = true
			}
			return true
		})
	}
	return nil
}

func (e *eventNames) saw(typ string) bool {
	e.mu.Lock()
	defer e.mu.Unlock()
	return e.types[typ]
}

func (*eventNames) Shutdown(context.Context) error   { return nil }
func (*eventNames) ForceFlush(context.Context) error { return nil }
Output:
true true

func Signals

func Signals(traces, logs bool) DestOption

Signals selects which signals this destination takes. The defaults are per destination (Langfuse is traces only; the rest both).

func Timeout

func Timeout(d time.Duration) DestOption

Timeout sets the destination's export request timeout: an OTLP request's, or a Sink's per-export deadline (default 2 s; past it the export is abandoned and its records counted dropped). A Sink backed by a store that may wait on a lock — SQLite with a busy_timeout — needs a Timeout no shorter than that wait.

func WithContent

func WithContent(cfg ...ContentConfig) DestOption

WithContent turns content on for this destination, optionally overriding the pipeline's ContentConfig.

type LoggerProvider

type LoggerProvider struct {
	*sdklog.LoggerProvider
	// contains filtered or unexported fields
}

LoggerProvider is the pipeline's OpenTelemetry logger provider: the SDK provider every method of which it forwards, plus the marker the core asks before it builds a raw record (ADR 0028 §12). A stock SDK provider has no marker, so an agent handed one never records wire bodies, whatever its processors answer Enabled.

func (*LoggerProvider) DevDetail

func (p *LoggerProvider) DevDetail() bool

DevDetail reports whether this pipeline records the development detail level: otel.DevDetail() and the dev gate at Start. It is the duck-typed marker the core asks before it starts a layer span or keeps a repair's original arguments (ADR 0016's 2026-10-26 amendment); the destinations still decide (first-party ones with content on only).

func (*LoggerProvider) RawBodies

func (p *LoggerProvider) RawBodies() bool

RawBodies reports whether this pipeline records provider wire bodies: otel.RawBodies(true) and the dev gate at Start (WEFT_ENV=dev read without NoEnv, or otel.DevMode unless an explicit WEFT_ENV overrules it). It is the duck-typed marker core.Reporter.WantsRaw asks for; the destinations still decide per chain (first-party ones only).

type LossError added in v0.24.0

type LossError struct {
	Lost          int64            // the total
	ByDestination map[string]int64 // destination name → records lost
}

LossError counts the records a pipeline lost, per destination name: failed or abandoned exports, a full queue's refusals, records a destination could not shape safely — not those a destination's policy filters by design. It matches ErrRecordsLost.

func (*LossError) Error added in v0.24.0

func (e *LossError) Error() string

func (*LossError) Is added in v0.24.0

func (e *LossError) Is(target error) bool

Is matches ErrRecordsLost.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option configures the pipeline (Install/Start).

func Content

func Content(cfg ContentConfig) Option

Content sets the pipeline-wide default for destinations with content on; a destination's WithContent overrides it.

func Datadog

func Datadog(opts ...DestOption) Option

Datadog exports to the local Datadog Agent's OTLP intake (http://localhost:4318; the Agent binds the standard OTLP ports when its OTLP receiver is enabled). Content off, traces + logs, SDK default batching. DatadogEndpoint overrides the URL.

func DevDetail

func DevDetail() Option

DevDetail turns on the development detail level (ADR 0016's 2026-10-26 amendment): beside RawBodies, the record shows the whole middleware onion. Each model call and tool call gets one "layer <name>" span per WrapModel / WrapTools layer (weft.layer.name, weft.layer.kind, weft.layer.index; error.type where the layer returned an error), nested outer to inner under its chat or execute_tool span, a weft.repair event carries the original arguments mw.RepairJSON replaced (capped at 4 KiB), and a contained tool or middleware panic's stack rides its execute_tool span as a weft.panic event (16 KiB) — neither under content off. Off by default: a span per layer is 2–6 more spans per call for a signal most calls do not need. Like RawBodies it is for development only — it takes effect only when the pipeline starts under the dev gate (WEFT_ENV=dev read unless NoEnv, or DevMode); otherwise Start logs one WARN ("otel: DevDetail ignored: …") and the pipeline behaves as without it — and only first-party destinations with content on receive the detail: any other destination gets the run without its layer spans and without the original arguments. The gate is the pipeline's LoggerProvider marker (LoggerProvider.DevDetail), which the core asks: pass Pipeline.LoggerProvider() to weft.LoggerProvider, or rely on Install's global registration. With the option the agent knows the level at New and builds the layer boundaries into its one model chain. Through the global provider it cannot (the pipeline may register after New): the first run builds a second chain, so the WrapModel constructors run twice — a stateful middleware holds two states — and a caller streaming Agent.Model() itself (weft/thread's compaction summary) gets the plain chain, without layer spans.

Example

DevDetail records the whole middleware onion in development: one "layer <name>" span per WrapModel / WrapTools layer per call, nested under the call's own span, for the first-party destinations (here the app's own exporter, marked FirstParty).

package main

import (
	"context"
	"fmt"
	"log"
	"strings"

	"github.com/weftbase/weft"
	"github.com/weftbase/weft/mw"
	"github.com/weftbase/weft/otel"
	"github.com/weftbase/weft/wefttest"
	"go.opentelemetry.io/otel/sdk/trace/tracetest"
)

func main() {
	spans := tracetest.NewInMemoryExporter()
	p, err := otel.Start(context.Background(),
		otel.NoEnv(), otel.DevMode(), otel.NoGlobal(),
		otel.Exporters(spans, nil, otel.FirstParty()),
		otel.DevDetail(),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = p.Shutdown(context.Background()) }()

	lookup := weft.Tool("lookup", "", func(context.Context, struct{}) (string, error) { return "found", nil })
	agt := weft.New(wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{Name: "lookup"}),
		wefttest.Say("done")),
		lookup, weft.WrapTools(mw.Audit(nil), mw.Allow(nil)),
		weft.TracerProvider(p.TracerProvider()), weft.LoggerProvider(p.LoggerProvider()))
	if _, err := agt.Generate(context.Background(), weft.Prompt("look it up")); err != nil {
		log.Fatal(err)
	}
	_ = p.ForceFlush(context.Background())
	for _, s := range spans.GetSpans() {
		if !strings.HasPrefix(s.Name, "layer ") {
			continue
		}
		for _, kv := range s.Attributes {
			if kv.Key == "weft.layer.index" {
				fmt.Println(s.Name, kv.Value.String())
			}
		}
	}
}
Output:
layer mw.Audit 0
layer mw.Allow 1

func DevMode

func DevMode() Option

DevMode attests in code that this pipeline runs in development: it satisfies the dev gate (ADR 0028 §12) that RawBodies, DevDetail and a destination's Blocking need, without reading the environment. It is the code-side twin of WEFT_ENV=dev, for tests and harnesses that control their own process — typically beside NoEnv, which reads no WEFT_ENV and so refuses all three on its own. It unlocks those three and nothing else: no destination follows from it. The gate still applies — a production binary never sets DevMode; the attestation has only moved from the process environment into code. The operator's environment wins: when the pipeline reads it (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; it opens the gate under NoEnv or with WEFT_ENV unset. Whenever DevMode is what opened it, Start logs one INFO line per switch it unlocked ("otel: raw bodies on by otel.DevMode()", "otel: dev detail on by otel.DevDetail() under otel.DevMode()", "otel: Blocking on by otel.DevMode()"), so a binary that ships it is visible.

Example

DevMode is the code-side twin of WEFT_ENV=dev, for a test or harness that controls its own process: beside NoEnv — which reads no OTEL_* variable, and no WEFT_ENV either — it is what lets an isolated pipeline record provider wire bodies (RawBodies) or make a destination wait for queue room (Blocking). Without it, Start would WARN "otel: RawBodies ignored: otel.NoEnv reads no WEFT_ENV" and record no weft.raw.

package main

import (
	"context"
	"fmt"
	"log"
	"sync"

	"go.opentelemetry.io/otel/attribute"
	sdklog "go.opentelemetry.io/otel/sdk/log"

	"github.com/weftbase/weft/otel"
)

func main() {
	p, err := otel.Start(context.Background(),
		otel.NoEnv(), otel.DevMode(), otel.NoGlobal(),
		otel.Exporters(nil, &eventNames{}, otel.FirstParty()),
		otel.RawBodies(true),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer func() { _ = p.Shutdown(context.Background()) }()
	fmt.Println(p.LoggerProvider().RawBodies())
}

// eventNames is a log exporter that remembers the weft.event.type of
// every record it exported.
type eventNames struct {
	mu    sync.Mutex
	types map[string]bool
}

func (e *eventNames) Export(_ context.Context, recs []sdklog.Record) error {
	e.mu.Lock()
	defer e.mu.Unlock()
	if e.types == nil {
		e.types = map[string]bool{}
	}
	for _, r := range recs {
		r.WalkAttributes(func(kv attribute.KeyValue) bool {
			if kv.Key == "weft.event.type" {
				e.types[kv.Value.AsString()] = true
			}
			return true
		})
	}
	return nil
}

func (e *eventNames) saw(typ string) bool {
	e.mu.Lock()
	defer e.mu.Unlock()
	return e.types[typ]
}

func (*eventNames) Shutdown(context.Context) error   { return nil }
func (*eventNames) ForceFlush(context.Context) error { return nil }
Output:
true

func Environment

func Environment(opts ...Option) Option

Environment marks opts' destinations as environment destinations, for a package that reads variables of its own (a viewer's URL and token): like OTEL_EXPORTER_OTLP_ENDPOINT's, they are dropped under NoEnv, de-duplicated by URL against the destinations named in code (the explicit one wins), and they do not count as named in code — under Install, environment destinations that all fail to build leave the Fallback in charge. Only the destinations among opts count; any other option inside it is ignored.

func Exporters

func Exporters(spans sdktrace.SpanExporter, logs sdklog.Exporter, opts ...DestOption) Option

Exporters wires your own exporters (vendor-specific, stdout, tests): whichever is non-nil gets a chain. Content off, SDK default batching; FirstParty marks them as yours (content on, raw bodies and app logs eligible). Sink is the synchronous form.

func Fallback

func Fallback(opts ...Option) Option

Fallback names destinations used only when the pipeline would otherwise have none: no destination option and no environment destination (OTEL_EXPORTER_OTLP_ENDPOINT, or one Environment marks) — and, under Install, when only environment destinations were configured and every one failed to build (one WARN). A program that names its own destinations never gets a fallback one. Only the destinations among opts count; any other option inside it is ignored.

func Heartbeat

func Heartbeat(every time.Duration) Option

Heartbeat sets how often the run tracker emits one weft.heartbeat record per open run (the default 10s; 0 or less disables). Three missed intervals are what obsdb's InterruptedAfter reads as interrupted.

func Langfuse

func Langfuse(host, publicKey, secretKey string, opts ...DestOption) Option

Langfuse exports traces to Langfuse's OTLP endpoint (<host>/api/public/otel/v1/traces, Basic auth base64(pk:sk); OTLP/HTTP only — gRPC is not accepted). Traces only: weft's spans carry no content (ADR 0016 O7) and Langfuse ingests traces, so it gets timing, usage, tool names and the identity chain; span-level content is the post-v1 follow-up F1.

func NoEnv

func NoEnv() Option

NoEnv ignores the OTEL_* destination variables (envDestinations). Explicit options are unaffected. It reads nothing, WEFT_ENV included: under NoEnv the development gate RawBodies and Blocking need holds only with DevMode (Start's WARN says "otel.NoEnv reads no WEFT_ENV" otherwise). The resource still reads OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES (the SDK's own detector). The value is comparable (opt == otel.NoEnv()), for a wrapper that reads variables of its own.

func NoGlobal

func NoGlobal() Option

NoGlobal leaves the OTel globals alone (Start only; Install always registers). For tests and dependency-injected programs. It isolates the globals only; NoEnv drops the environment destinations. The value is comparable (opt == otel.NoGlobal()).

func OTLP

func OTLP(endpoint string, opts ...DestOption) Option

OTLP exports to any OTLP/HTTP endpoint (http(s)://host:port). Content off, traces + logs, SDK default batching; Headers adds request headers. FirstParty marks an endpoint you operate yourself (your own collector, a local viewer): content on, raw bodies and app logs eligible.

func Options

func Options(opts ...Option) Option

Options bundles opts into one Option — for a package that offers a preset made of several of otel's own options. The result is a pointer, so it is comparable: a wrapper may recognise the presets it handed out among the options it is given.

func RawBodies

func RawBodies(on bool) Option

RawBodies records each model call attempt's wire exchange — the provider request and response the first-party adapters sent and received, headers included minus the credential ones, each body capped at 256 KiB — as one weft.raw record per attempt (ADR 0028 §12), for first-party destinations only (a Sink, or one marked FirstParty; never Datadog, Langfuse, or an OTLP or Exporters destination without FirstParty, whatever its content setting, and not a first-party destination under NoContent). Off by default, and refused outside development: it takes effect only when the pipeline starts under the dev gate — WEFT_ENV is "dev" (read unless NoEnv), or DevMode attests it in code (under NoEnv, or with WEFT_ENV unset; an explicit WEFT_ENV other than dev wins, "otel: DevMode ignored: WEFT_ENV=<value>"). Otherwise Start logs one WARN line naming the cause ("otel: RawBodies ignored: WEFT_ENV is not dev", or under NoEnv without DevMode "otel: RawBodies ignored: otel.NoEnv reads no WEFT_ENV") and the pipeline behaves as if the option were absent: no destination asks for weft.raw, so the adapters buffer nothing (core.Reporter.WantsRaw is false). The gate is the pipeline's LoggerProvider marker (LoggerProvider.RawBodies): pass Pipeline.LoggerProvider() to weft.LoggerProvider, or rely on Install's global registration — a stock SDK provider never records raw bodies. Under it a first-party batch destination's log batch is capped at 16 records and each export is split at 12 MiB, keeping every post under a 16 MiB ingest limit: a raw record is ≈ 650 KiB with two full ordinary bodies and at worst ≈ 3 MiB (bodies of control bytes, each six bytes in JSON; it is encoded without HTML escaping).

func Resource

func Resource(r *sdkresource.Resource) Option

Resource merges r over the detected resource.

func Sampler

func Sampler(s sdktrace.Sampler) Option

Sampler sets the trace sampler (default ParentBased(AlwaysOn)). Records are log records; sampling never applies to them.

func Service

func Service(name string) Option

Service sets resource service.name. Else OTEL_SERVICE_NAME, else the binary's name.

func Sink

func Sink(name string, open SinkOpener, opts ...DestOption) Option

Sink is a destination written synchronously: open runs at Start and its exporters are driven through simple processors — each record is exported before Emit returns, with no queue (a crash loses nothing emitted; the export cost rides the run's goroutine). Blocking and QueueSize do not apply. Each export is bounded by the destination's Timeout (default 2 s): telemetry never blocks control, so a Sink that hangs costs the run at most that long — the export is abandoned and its records counted dropped, and while it is still stuck every later record is dropped at once, until it returns. The deadline is the Timeout's alone: a record emitted on a canceled context (a run's tail after its cancellation) is still written. A Sink whose export can wait longer than 2 s by design — a SQLite store with a long busy_timeout behind another writer — should set Timeout to at least that wait, or its records are dropped while the store would have taken them. The pipeline's Shutdown waits for an abandoned export still running before it shuts the exporters down, and leaves them open (an error says so) rather than call Shutdown under a running Export. A Sink is first-party (FirstParty): content on, raw bodies, the dev detail and app logs eligible. An export error is counted as the destination's drop and named by its throttled WARN, never handed to OTel's global error handler. The exporters' Shutdown runs at the pipeline's Shutdown (after the flush), or at once when the pipeline fails to build. name labels the destination's WARN lines and drop counter.

func Slog

func Slog() Option

Slog bridges the program's default logger: once the pipeline is registered, slog.SetDefault wraps the default's handler with SlogHandler (bound to this pipeline), so every slog.Default line — weft.Logger's run lines (their default is slog.Default, read at log time), mw.Log(nil), mw.Audit(slog.Default()), the app's own — that is logged under a span reaches the pipeline's app-log destinations (AppLogs) as well as where it went before. Shutdown restores the previous default and the log package's writer and flags (unless the program replaced the default since).

A program still on slog's built-in default handler (it never called slog.SetDefault) keeps its lines on the log package's writer, written by a slog.TextHandler at the level slog.SetLogLoggerLevel set (INFO unless changed; read once, at Install), each line after log.Prefix() — wrapping the built-in handler itself would deadlock the log package. The format changes while the bridge is installed: the TextHandler's key=value lines (time=… level=… msg=…) replace the built-in "2009/11/10 23:00:00 INFO msg k=v" form, and the log package's flags no longer shape them; both come back at shutdown.

One Slog pipeline at a time: a second Install(…, Slog()) wraps the first's bridge. Shut them down in reverse order; out of order, the last shutdown still skips a closed pipeline's wrap and restores what the first found. Under NoGlobal (Start only) the default is left alone, like the OTel globals; bind a handler with Pipeline.SlogHandler instead.

Example

Slog bridges slog.Default: weft's own Debug run lines (weft.Logger's default is slog.Default) and mw.Log's (whose nil logger is too) reach the pipeline's first-party destinations, each under the span it was logged in — a viewer's app logs for the run.

package main

import (
	"context"
	"fmt"
	"log"
	"sync"

	"github.com/weftbase/weft"
	"github.com/weftbase/weft/mw"
	"github.com/weftbase/weft/otel"
	"github.com/weftbase/weft/wefttest"
	"go.opentelemetry.io/otel/attribute"

	sdklog "go.opentelemetry.io/otel/sdk/log"
)

// memLogs is an in-memory log exporter: the examples' stand-in for a
// store or a collector.
type memLogs struct {
	mu   sync.Mutex
	recs []sdklog.Record
}

func (m *memLogs) Export(_ context.Context, recs []sdklog.Record) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	for _, r := range recs {
		m.recs = append(m.recs, r.Clone())
	}
	return nil
}

func (m *memLogs) Shutdown(context.Context) error   { return nil }
func (m *memLogs) ForceFlush(context.Context) error { return nil }

// attr reads one string attribute off a record.
func attr(r sdklog.Record, key string) string {
	var out string
	r.WalkAttributes(func(kv attribute.KeyValue) bool {
		if string(kv.Key) == key {
			out = kv.Value.String()
			return false
		}
		return true
	})
	return out
}

// appLogs is the records the slog bridge teed: they carry no weft
// record kind.
func (m *memLogs) appLogs() []sdklog.Record {
	m.mu.Lock()
	defer m.mu.Unlock()
	var out []sdklog.Record
	for _, r := range m.recs {
		if attr(r, "weft.record") == "" && r.EventName() == "" {
			out = append(out, r)
		}
	}
	return out
}

func main() {
	logs := &memLogs{}
	shutdown := otel.Install(otel.NoEnv(), otel.Exporters(nil, logs, otel.FirstParty()), otel.Slog())

	agt := weft.New(wefttest.Script(wefttest.Say("all done")),
		weft.Name("example"), weft.WrapModel(mw.Log(nil)))
	if _, err := agt.Generate(context.Background(), weft.Prompt("go")); err != nil {
		log.Fatal(err)
	}
	shutdown() // flushes, and puts slog.Default back

	for _, l := range logs.appLogs() {
		fmt.Println(l.Severity(), l.Body().AsString())
	}
}
Output:
DEBUG run start
DEBUG model request
DEBUG model finish
DEBUG model call
DEBUG run finish

func Tag

func Tag(tag any, opts ...Option) Option

Tag wraps opts in one Option that carries tag, for a package that wraps otel and hands out its own destinations (a store's sink, a viewer's endpoint): TagOf recognises the option among the ones it is handed, and a pipeline lists tag among its Tags for every destination of opts it built — nested in Options, Fallback or Environment included, never one Install skipped or a Fallback left unused. The tag is opaque to otel; a pointer the wrapper owns is the usual one.

type Pipeline

type Pipeline struct {
	// contains filtered or unexported fields
}

Pipeline is the running fan-out: one TracerProvider and one LoggerProvider, one processor chain per destination, one run tracker. Create it with Start (or Install, which never fails).

func Installed

func Installed() *Pipeline

Installed returns the pipeline Install (or Start without NoGlobal) registered globally; nil before that and after its Shutdown. A package that wraps otel uses it to tell which pipeline is live.

func Start

func Start(ctx context.Context, opts ...Option) (*Pipeline, error)

Start builds and starts the pipeline: one provider pair, the run tracker, one processor chain per destination (explicit options and environment combined, de-duplicated with the explicit destination winning). It fails if any destination fails to build — what was already built is shut down again, exporters handed to Exporters included; NoGlobal leaves the OTel globals alone (tests).

func (*Pipeline) Destinations

func (p *Pipeline) Destinations() []string

Destinations names the destinations the pipeline built, in order — each one's label (Name, or the kind's: "otlp", "otlp(env)", "datadog", …). A destination Install skipped is not among them.

func (*Pipeline) ForceFlush

func (p *Pipeline) ForceFlush(ctx context.Context) error

ForceFlush flushes every destination, all at once: each destination's span and log chains flush on their own goroutines under ctx, so a slow or hung destination costs only its own data, never the budget of the one behind it (flushed through the providers they go one after another).

func (*Pipeline) LoggerProvider

func (p *Pipeline) LoggerProvider() *LoggerProvider

LoggerProvider returns the pipeline's logger provider: the SDK's, carrying the raw-record marker (RawBodies).

func (*Pipeline) Shutdown

func (p *Pipeline) Shutdown(ctx context.Context) error

Shutdown runs S2.4's order: stop heartbeats → flush every destination in parallel → shut down the providers → shut every Sink's exporters down last. Every wait in it is bounded by ctx: a destination stuck in a write (a Sink behind another process's lock, a hung exporter) costs the caller its context, never more. The flush takes at most half of what ctx has left (5 s at most), so the providers' own shutdown — the batch processors' last export — always gets a slice of its own.

Loss is reported, never silent (WR-36): Shutdown returns the flush's and every provider's and Sink's shutdown errors joined, and, when any record was lost during the pipeline's life or its shutdown — a failed or abandoned export, a full queue's refusal, a record a destination could not shape safely — a *LossError matching ErrRecordsLost that counts them per destination. Records a destination's policy filtered by design (deltas under NoDeltas, raw bodies a third party never takes) are not losses. Shutdown runs once; a concurrent or later call returns the first's result, or its own ctx's error should that come first.

func (*Pipeline) SlogHandler

func (p *Pipeline) SlogHandler(next slog.Handler) slog.Handler

SlogHandler is the package-level SlogHandler bound to this pipeline rather than the installed one — for NoGlobal pipelines and tests. It marks the pipeline as bridged (weft.logs.bridged) from now on.

func (*Pipeline) Tags

func (p *Pipeline) Tags() []any

Tags returns the tags (Tag) of the destinations the pipeline built, in destination order, a destination's innermost tag first.

func (*Pipeline) TracerProvider

func (p *Pipeline) TracerProvider() *sdktrace.TracerProvider

TracerProvider returns the pipeline's tracer provider.

type SinkOpener

type SinkOpener func(ctx context.Context) (sdktrace.SpanExporter, sdklog.Exporter, error)

SinkOpener opens a Sink's exporters when the pipeline starts. Either may be nil (that signal is not taken); an error fails the destination like any other.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL