tracer

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: MIT Imports: 25 Imported by: 1

Documentation

Overview

Package tracer instruments AWS Lambda handlers using OpenTelemetry.

New creates a Tracer. WrapHandler traces a typed Lambda invocation, Capture traces an operation, and Tracer.StartSpan supports manual spans. Always pass the returned span context to downstream operations and end the span.

Providers and export

NewOTelBackend accepts an application-owned OpenTelemetry provider without installing globals or taking ownership of it. The default backend configures OTLP export; deliver traces to AWS X-Ray through a collector's awsxray exporter. Tracer.HTTPClient and Tracer.InstrumentAWS instrument outbound calls. The application owns shutdown for a supplied provider; review flush behavior when composing Lambda wrappers.

ExtractLambdaHTTPContext is an opt-in incoming propagation callback. Choose whether request headers are trusted and whether responses or errors may contain sensitive data before enabling capture. The separate tracer/xray SDK adapter is deprecated and frozen; use this OpenTelemetry integration for new applications.

For usage and compatibility details, see the user guide.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Capture

func Capture[R any](ctx context.Context, t *Tracer, name string, operation func(context.Context) (R, error)) (result R, err error)

Capture wraps an arbitrary operation, preserving its typed result and error.

func ExtractHTTPContext

func ExtractHTTPContext(ctx context.Context, headers http.Header) context.Context

ExtractHTTPContext explicitly reads W3C and X-Ray propagation headers. Existing valid OTel context takes precedence; cancellation and deadlines survive. Use this in HandlerOptions.ExtractContext for HTTP-triggered Lambda events.

func ExtractLambdaHTTPContext

func ExtractLambdaHTTPContext(ctx context.Context, event any) context.Context

ExtractLambdaHTTPContext is an opt-in HandlerOptions.ExtractContext callback for API Gateway, Function URL, ALB and AppSync HTTP header envelopes. Existing context wins; multiValueHeaders overrides headers. Invalid/non-HTTP events are ignored. Applications choose whether incoming propagation headers are trusted.

func WrapHandler

func WrapHandler[T, R any](t *Tracer, handler func(context.Context, T) (R, error), options ...HandlerOptions) func(context.Context, T) (R, error)

WrapHandler captures one handler operation, preserves business errors/panics, and attempts a bounded flush after ending the span, including error paths.

Types

type Backend

type Backend interface {
	Start(context.Context, string, Kind) (context.Context, Span, error)
	HTTPTransport(http.RoundTripper) http.RoundTripper
	InstrumentAWS(*[]func(*middleware.Stack) error)
	ForceFlush(context.Context) error
	Shutdown(context.Context) error
}

Backend owns instrumentation mechanics. Implementations must be concurrency-safe. Shutdown must not close a provider owned by the application unless explicitly agreed. ForceFlush must honor context cancellation and deadlines; the wrapper cannot forcibly stop a custom implementation that ignores its context.

type HandlerOptions

type HandlerOptions struct {
	Name                   string
	DisableCaptureResponse bool
	ExtractContext         func(context.Context, any) context.Context
}

HandlerOptions allows response suppression and custom event context extraction. Extraction must preserve the parent context's deadline and invocation metadata.

type Kind

type Kind int
const (
	Internal Kind = iota
	Handler
)

type OTelBackend

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

OTelBackend integrates an application-owned OpenTelemetry provider. Metadata is represented as JSON attributes; see docs/COMPATIBILITY.md.

func NewOTelBackend

func NewOTelBackend(provider trace.TracerProvider) *OTelBackend

NewOTelBackend does not install globals or take ownership of the provider.

Example
package main

import (
	"context"
	"fmt"

	"github.com/rambow-cloud/powertools-lambda-go/tracer"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
)

func main() {
	// Production providers can export OTLP to a collector using awsxray.
	// This provider has no exporter, so the example performs no network calls.
	provider := sdktrace.NewTracerProvider(sdktrace.WithSampler(sdktrace.AlwaysSample()))
	defer func() { _ = provider.Shutdown(context.Background()) }()
	backend := tracer.NewOTelBackend(provider)
	// Direct backend operations use the supplied provider independently of
	// the environment flags that control a Tracer instance.
	_, span, err := backend.Start(context.Background(), "accept-order", tracer.Internal)
	if err != nil {
		panic(err)
	}
	fmt.Println(span.TraceID() != "")
	span.End()
}
Output:
true

func (*OTelBackend) ForceFlush

func (b *OTelBackend) ForceFlush(ctx context.Context) error

func (*OTelBackend) HTTPTransport

func (b *OTelBackend) HTTPTransport(base http.RoundTripper) http.RoundTripper

func (*OTelBackend) InstrumentAWS

func (b *OTelBackend) InstrumentAWS(options *[]func(*middleware.Stack) error)

func (*OTelBackend) Shutdown

func (b *OTelBackend) Shutdown(ctx context.Context) error

func (*OTelBackend) Start

func (b *OTelBackend) Start(ctx context.Context, name string, kind Kind) (context.Context, Span, error)

func (*OTelBackend) WithPropagator

func (b *OTelBackend) WithPropagator(p propagation.TextMapPropagator) *OTelBackend

WithPropagator configures propagation before the backend is used by handlers.

type Option

type Option func(*config)

func WithBackend

func WithBackend(backend Backend) Option

func WithCaptureError

func WithCaptureError(enabled bool) Option

func WithCaptureHTTP

func WithCaptureHTTP(enabled bool) Option

func WithCaptureResponse

func WithCaptureResponse(enabled bool) Option

func WithEnabled

func WithEnabled(enabled bool) Option

func WithErrorHandler

func WithErrorHandler(handler func(error)) Option

func WithFlushTimeout

func WithFlushTimeout(timeout time.Duration) Option

func WithLocalTracing

func WithLocalTracing(enabled bool) Option

WithLocalTracing explicitly permits tracing outside Lambda for development/tests.

func WithServiceName

func WithServiceName(name string) Option

type Span

type Span interface {
	Annotation(string, any) error
	Metadata(namespace, key string, value any) error
	RecordError(error, bool)
	End()
	TraceID() string
	Sampled() bool
}

Span is the common surface supported by OpenTelemetry and the optional X-Ray backend.

type Tracer

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

func New

func New(options ...Option) (*Tracer, error)

New defaults to OpenTelemetry with an OTLP/HTTP exporter. The exporter uses the standard OTEL_EXPORTER_OTLP_* environment settings; no global provider is changed. Disabled tracers create no exporter. Initialize once outside the Lambda handler.

func (*Tracer) AddResponseAsMetadata

func (t *Tracer) AddResponseAsMetadata(ctx context.Context, name string, value any)

AddResponseAsMetadata respects the tracer's response-capture configuration.

func (*Tracer) AnnotateInvocation

func (t *Tracer) AnnotateInvocation(ctx context.Context)

AnnotateInvocation adds the shared cold-start identity and configured service. It does not create a new invocation or change the active span.

func (*Tracer) Backend

func (t *Tracer) Backend() Backend

func (*Tracer) Enabled

func (t *Tracer) Enabled() bool

func (*Tracer) Flush

func (t *Tracer) Flush(ctx context.Context) error

func (*Tracer) HTTPClient

func (t *Tracer) HTTPClient(client *http.Client) *http.Client

HTTPClient copies the client and instruments its transport without global patching.

func (*Tracer) InstrumentAWS

func (t *Tracer) InstrumentAWS(options *[]func(*middleware.Stack) error)

InstrumentAWS modifies SDK v2 APIOptions during client construction only.

func (*Tracer) IsTraceSampled

func (t *Tracer) IsTraceSampled(ctx context.Context) bool

func (*Tracer) PutAnnotation

func (t *Tracer) PutAnnotation(ctx context.Context, key string, value any) error

func (*Tracer) PutMetadata

func (t *Tracer) PutMetadata(ctx context.Context, key string, value any, namespace ...string) error

func (*Tracer) Shutdown

func (t *Tracer) Shutdown(ctx context.Context) error

func (*Tracer) StartSpan

func (t *Tracer) StartSpan(ctx context.Context, name string) (context.Context, func(error))

StartSpan starts an internal operation and returns an idempotent completion function. Pass the returned context to nested work; the caller's context remains unchanged.

func (*Tracer) TraceID

func (t *Tracer) TraceID(ctx context.Context) string

func (*Tracer) XRayTraceID

func (t *Tracer) XRayTraceID(ctx context.Context) string

XRayTraceID returns the current trace ID in the X-Ray display/wire format. It supports OTel contexts without requiring the retired X-Ray SDK adapter.

Jump to

Keyboard shortcuts

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