package traces

Import Path
	go.pact.im/x/traces (on go.dev)

Dependency Relation
	imports 10 packages, and imported by 10 packages

Involved Source Files attr.go Package traces provides distributed tracing primitives. Create a [Tracer] with [New] and pass it explicitly to instrumented code. Call [Tracer.Start] with an explicit parent [SpanRef] (a zero value starts a new trace) and finish spans with [Span.End] or [EndError]. Use [NewContext] and [FromContext] to carry a [SpanRef] across API boundaries. By convention, accept [SpanRef] when a function only needs a parent for its own spans, and accept [Span] when it is meant to annotate the caller’s span. handler.go ids.go record.go sampler.go span.go spanref.go tracer.go
Code Examples package main import ( "context" "fmt" "go.pact.im/x/traces" "go.pact.im/x/traces/tracestest" ) func main() { rec := &tracestest.Recorder{} tr := traces.New(rec).WithScope("example.com/users") loadProfile := func(ctx context.Context, parent traces.SpanRef, userID string) (err error) { sp := tr.Start(ctx, parent, traces.SpanKindInternal, "loadProfile", traces.String("user.id", userID), ) defer traces.EndError(ctx, sp, &err) return nil } ctx := context.Background() root := tr.Start(ctx, traces.SpanRef{}, traces.SpanKindServer, "GET /users/{id}") _ = loadProfile(ctx, root.Ref(), "42") root.End(ctx) fmt.Println(len(rec.Records())) }
Package-Level Type Names (total 21, in which 16 are exported)
/* sort exporteds by: | */
Attr is a key-value attribute attached to a span or resource. Scalar and string values are stored inline without heap allocations. Key is the attribute name. Encode writes the attribute’s value into e. func Array(k string, f func(elem Encoder)) Attr func Bool(k string, v bool) Attr func Bytes(k string, b []byte) Attr func Duration(k string, d time.Duration) Attr func Float64(k string, v float64) Attr func Int(k string, v int) Attr func Int64(k string, v int64) Attr func Map(k string, attrs ...Attr) Attr func Marshal(k string, m Marshaler) Attr func String(k, v string) Attr func Stringer(k string, v fmt.Stringer) Attr func Strings(k string, vs ...string) Attr func Map(k string, attrs ...Attr) Attr func (*Span).SetAttrs(attrs ...Attr) func (*Tracer).Start(ctx context.Context, parent SpanRef, kind SpanKind, name string, attrs ...Attr) *Span func (*Tracer).WithAttrs(attrs ...Attr) *Tracer
Encoder encodes a single attribute value into a backend-specific representation. Array encodes a sequence of values by invoking f with an element [Encoder]. Each method call on elem appends one element to the array. Bool encodes a bool value. Bytes encodes a byte slice value. Float64 encodes a float64 value. Int64 encodes an int64 value. Map encodes a key-value map by invoking f with a field constructor. Calling field(key) returns an [Encoder] for that entry’s value. String encodes a string value. func Attr.Encode(e Encoder) func Marshaler.MarshalTrace(e Encoder) func MarshalerFunc.MarshalTrace(e Encoder)
Handler receives finished span [Record] values from a [Tracer]. Implementations must be safe for concurrent use. Handle processes a finished span record. HandlerFunc *go.pact.im/x/traces/batchtraces.Batcher *go.pact.im/x/traces/tracestest.Recorder func DiscardHandler() Handler func (*Tracer).Handler() Handler func go.pact.im/x/traces/batchtraces.Passthrough(exp batchtraces.Exporter) Handler func New(h Handler) *Tracer
HandlerFunc is a function that implements the [Handler] interface. Handle implements the [Handler] interface. HandlerFunc : Handler
IDSource generates trace and span identifiers for a [Tracer]. Implementations must be safe for concurrent use and must return valid (non-zero) identifiers. NewSpanID returns a new valid [SpanID]. NewTraceID returns a new valid [TraceID]. func RandomIDs() IDSource func (*Tracer).WithIDs(ids IDSource) *Tracer
Marshaler encodes itself into an [Encoder]. It is invoked lazily by consumers (such as exporters or test recorders) and is never called for unsampled or discarded spans. Implementations must remain safe to read until export completes. MarshalTrace encodes the value into e. MarshalerFunc func Marshal(k string, m Marshaler) Attr
MarshalerFunc is a function that implements the [Marshaler] interface. MarshalTrace implements the [Marshaler] interface. MarshalerFunc : Marshaler
Record is an immutable snapshot of a finished span delivered to a [Handler]. Handlers must not modify slices contained in Record. Because the span has already ended and its storage is never reused by [Tracer], handlers may retain a Record past the return of [Handler.Handle]. Attrs holds the span’s recorded attributes. End is the time when the span ended. Err is the error recorded on the span, if any. Kind is the span kind. Name is the span name. Parent is the parent span reference, or zero for root spans. Ref is the identity of this span. Scope identifies the instrumentation scope that created the span. Start is the time when the span started. func go.pact.im/x/traces/tracestest.(*Recorder).Find(name string) (Record, bool) func go.pact.im/x/traces/tracestest.(*Recorder).Records() []Record func Handler.Handle(ctx context.Context, rec Record) error func HandlerFunc.Handle(ctx context.Context, rec Record) error func go.pact.im/x/traces/batchtraces.(*Batcher).Handle(_ context.Context, rec Record) error func go.pact.im/x/traces/batchtraces.Exporter.Export(ctx context.Context, batch []Record) error func go.pact.im/x/traces/batchtraces.ExporterFunc.Export(ctx context.Context, batch []Record) error func go.pact.im/x/traces/otlptraces.(*Exporter).Export(ctx context.Context, batch []Record) error func go.pact.im/x/traces/tracestest.Attr(rec Record, key string) (any, bool) func go.pact.im/x/traces/tracestest.IsChild(parent, child Record) bool func go.pact.im/x/traces/tracestest.(*Recorder).Handle(_ context.Context, rec Record) error
Sampler decides at span start whether a span should be recorded and marked sampled. func ParentBased(root Sampler) Sampler func Ratio(fraction float64) Sampler func ParentBased(root Sampler) Sampler func (*Tracer).WithSampler(s Sampler) *Tracer
SamplingParams contains the start-time inputs to a [Sampler]. Attrs holds the start-time attributes on the span. Kind is the span kind. Name is the initial span name. Parent is the parent span reference, or zero for root spans. Scope is the instrumentation scope of the [Tracer]. TraceID is the trace identifier assigned to the new span. func AlwaysSample(context.Context, SamplingParams) bool func NeverSample(context.Context, SamplingParams) bool
Span represents an in-flight span created by [Tracer.Start]. All methods are safe for concurrent use. On a non-recording span, mutation methods and [Span.End] are no-ops. End finishes the span and passes its [Record] to the tracer’s [Handler] with ctx. Subsequent calls to End are no-ops. IsRecording reports whether span data is being recorded. Ref returns the span’s immutable [SpanRef] for use as a parent or for propagation across process boundaries. SetAttrs sets attributes on the span, replacing any existing attribute with the same key. It has no effect after [Span.End]. SetError records an error on the span. A nil error is ignored. It has no effect after [Span.End]. SetName updates the span’s name (for example once an HTTP route pattern is known). It has no effect after [Span.End]. SetStart overrides the span’s start timestamp. It has no effect after [Span.End]. func (*Tracer).Start(ctx context.Context, parent SpanRef, kind SpanKind, name string, attrs ...Attr) *Span func EndError(ctx context.Context, sp *Span, errp *error)
SpanID is an 8-byte W3C span identifier. IsValid reports whether id is non-zero. String returns the 16-character lowercase hex encoding of id. SpanID : database/sql/driver.Validator SpanID : expvar.Var SpanID : fmt.Stringer func IDSource.NewSpanID() SpanID
SpanKind describes the role of a span in a trace. func (*Tracer).Start(ctx context.Context, parent SpanRef, kind SpanKind, name string, attrs ...Attr) *Span const SpanKindClient const SpanKindConsumer const SpanKindInternal const SpanKindProducer const SpanKindServer const SpanKindUnspecified
SpanRef is the immutable, comparable identity of a span propagated to child spans and across process boundaries. Sampled reports whether the span is sampled. SpanID identifies the span within the trace. TraceID identifies the trace. IsValid reports whether both [SpanRef.TraceID] and [SpanRef.SpanID] are valid. SpanRef : database/sql/driver.Validator func FromContext(ctx context.Context) SpanRef func (*Span).Ref() SpanRef func go.pact.im/x/traces/traceparent.Extract(get func(key string) []string) SpanRef func go.pact.im/x/traces/traceparent.Parse(s string) (SpanRef, error) func NewContext(ctx context.Context, ref SpanRef) context.Context func (*Tracer).Start(ctx context.Context, parent SpanRef, kind SpanKind, name string, attrs ...Attr) *Span func go.pact.im/x/traces/slogtraces.Attr(key string, ref SpanRef) slog.Attr func go.pact.im/x/traces/slogtraces.Value(ref SpanRef) slog.Value func go.pact.im/x/traces/traceparent.Format(ref SpanRef) string func go.pact.im/x/traces/traceparent.Inject(ref SpanRef, set func(key, value string))
TraceID is a 16-byte W3C trace identifier. IsValid reports whether id is non-zero. String returns the 32-character lowercase hex encoding of id. TraceID : database/sql/driver.Validator TraceID : expvar.Var TraceID : fmt.Stringer func IDSource.NewTraceID() TraceID
Tracer creates spans and delivers finished [Record] values to a [Handler]. A Tracer is immutable and safe for concurrent use; With* methods return a shallow copy with the updated setting (or the receiver if unchanged). Like [log/slog.Logger], a nil Tracer is invalid and panics on use. Pass [DiscardHandler] to [New] to disable tracing explicitly. Handler returns the underlying [Handler]. Start begins a new span with the given explicit parent, kind, name, and start-time attributes. A zero parent starts a new trace; a valid parent continues that trace (for example from [FromContext] or [Span.Ref]). The context ctx is passed through to the [Sampler] and is never inspected for an implicit parent. Every returned [Span] should eventually be finished by calling [Span.End]. WithAttrs returns a [Tracer] that includes attrs on every span it starts. If attrs is empty, it returns the receiver. WithIDs returns a [Tracer] using ids to generate trace and span identifiers. If ids is nil, it restores a fresh [RandomIDs] generator. WithSampler returns a [Tracer] using s for sampling decisions. If s is nil, it restores the default [ParentBased] sampler with [AlwaysSample]. WithScope returns a [Tracer] that attributes spans to the given instrumentation scope name. If name matches the current scope, it returns the receiver. WithTime returns a [Tracer] using now as its time source. If now is nil, it restores [time.Now]. func New(h Handler) *Tracer func (*Tracer).WithAttrs(attrs ...Attr) *Tracer func (*Tracer).WithIDs(ids IDSource) *Tracer func (*Tracer).WithSampler(s Sampler) *Tracer func (*Tracer).WithScope(name string) *Tracer func (*Tracer).WithTime(now func() time.Time) *Tracer func go.pact.im/x/traces/grpctraces.NewClientHandler(tr *Tracer) *grpctraces.Handler func go.pact.im/x/traces/grpctraces.NewServerHandler(tr *Tracer) *grpctraces.Handler func go.pact.im/x/traces/httptraces.NewHandler(tr *Tracer, next http.Handler) *httptraces.Handler func go.pact.im/x/traces/httptraces.NewTransport(tr *Tracer, base http.RoundTripper) *httptraces.Transport func go.pact.im/x/traces/otelbridge.NewProvider(tr *Tracer) *otelbridge.Provider func go.pact.im/x/traces/pgxtraces.New(tr *Tracer) *pgxtraces.Tracer
Package-Level Functions (total 23, in which 22 are exported)
AlwaysSample is a [Sampler] that samples every span.
Array returns an array [Attr] whose elements are encoded lazily by f.
Bool returns a bool [Attr].
Bytes returns a byte slice [Attr]. The caller must not modify b afterwards.
DiscardHandler returns a [Handler] that discards all span records. Passing DiscardHandler() to [New] disables span recording without allocating span state.
Duration returns an int64 nanoseconds [Attr].
EndError is a defer helper that calls [Span.SetError] when errp points to a non-nil error, and then calls [Span.End]: func doWork(ctx context.Context, tr *traces.Tracer) (err error) { sp := tr.Start(ctx, traces.FromContext(ctx), "doWork") defer traces.EndError(ctx, sp, &err) ... }
Float64 returns a float64 [Attr].
FromContext returns the [SpanRef] stored in ctx by [NewContext], or the zero [SpanRef] if none is present.
Int returns an int64 [Attr] from an int.
Int64 returns an int64 [Attr].
Map returns a nested key-value map [Attr]. The caller must not modify attrs afterwards.
Marshal returns an [Attr] encoded lazily via m. If m is nil, the attribute encodes nothing.
NeverSample is a [Sampler] that samples no spans.
New returns a new [Tracer] instance with the given non-nil [Handler]. It defaults to [ParentBased] with [AlwaysSample], [time.Now], and [RandomIDs].
NewContext returns a copy of ctx carrying ref. It is intended for crossing API boundaries that cannot accept a parent [SpanRef] explicitly.
ParentBased returns a [Sampler] that follows the parent’s Sampled flag when a valid parent is present, and delegates to root for root spans.
RandomIDs returns an [IDSource] backed by a ChaCha8 generator seeded from [crypto/rand]. It is safe for concurrent use.
Ratio returns a [Sampler] that deterministically samples fraction (in [0, 1]) of traces based on the rightmost 56 bits of the trace ID.
String returns a string [Attr].
Stringer returns a string [Attr] whose value is computed lazily via v.String during [Attr.Encode]. If v is nil, the attribute encodes nothing.
Strings returns a string array [Attr]. The caller must not modify vs afterwards.
Package-Level Constants (total 17, in which 6 are exported)
Span kinds.
Span kinds.
Span kinds.
Span kinds.
Span kinds.