otel: go.opentelemetry.io/otel/sdk/trace Index | Examples | Files

package trace

import "go.opentelemetry.io/otel/sdk/trace"

Package trace contains support for OpenTelemetry distributed tracing.

This package is currently in a pre-GA phase. Backwards incompatible changes may be introduced in subsequent minor version releases as we work to track the evolving OpenTelemetry specification and user feedback.

The following assumes a basic familiarity with OpenTelemetry concepts. See https://opentelemetry.io.



Package Files

attributesmap.go batch_span_processor.go config.go doc.go evictedqueue.go id_generator.go provider.go sampling.go simple_span_processor.go span.go span_processor.go trace_go11.go tracer.go


const (
    DefaultMaxQueueSize       = 2048
    DefaultBatchTimeout       = 5000 * time.Millisecond
    DefaultMaxExportBatchSize = 512
const (
    // DefaultMaxEventsPerSpan is default max number of message events per span
    DefaultMaxEventsPerSpan = 1000

    // DefaultMaxAttributesPerSpan is default max number of attributes per span
    DefaultMaxAttributesPerSpan = 1000

    // DefaultMaxLinksPerSpan is default max number of links per span
    DefaultMaxLinksPerSpan = 1000

type BatchSpanProcessor Uses

type BatchSpanProcessor struct {
    // contains filtered or unexported fields

BatchSpanProcessor is a SpanProcessor that batches asynchronously-received SpanSnapshots and sends them to a trace.Exporter when complete.

func NewBatchSpanProcessor Uses

func NewBatchSpanProcessor(exporter export.SpanExporter, options ...BatchSpanProcessorOption) *BatchSpanProcessor

NewBatchSpanProcessor creates a new BatchSpanProcessor that will send SpanSnapshot batches to the exporters with the supplied options.

The returned BatchSpanProcessor needs to be registered with the SDK using the RegisterSpanProcessor method for it to process spans.

If the exporter is nil, the span processor will preform no action.

func (*BatchSpanProcessor) ForceFlush Uses

func (bsp *BatchSpanProcessor) ForceFlush()

ForceFlush exports all ended spans that have not yet been exported.

func (*BatchSpanProcessor) OnEnd Uses

func (bsp *BatchSpanProcessor) OnEnd(s ReadOnlySpan)

OnEnd method enqueues a ReadOnlySpan for later processing.

func (*BatchSpanProcessor) OnStart Uses

func (bsp *BatchSpanProcessor) OnStart(parent context.Context, s ReadWriteSpan)

OnStart method does nothing.

func (*BatchSpanProcessor) Shutdown Uses

func (bsp *BatchSpanProcessor) Shutdown(ctx context.Context) error

Shutdown flushes the queue and waits until all spans are processed. It only executes once. Subsequent call does nothing.

type BatchSpanProcessorOption Uses

type BatchSpanProcessorOption func(o *BatchSpanProcessorOptions)

func WithBatchTimeout Uses

func WithBatchTimeout(delay time.Duration) BatchSpanProcessorOption

func WithBlocking Uses

func WithBlocking() BatchSpanProcessorOption

func WithMaxExportBatchSize Uses

func WithMaxExportBatchSize(size int) BatchSpanProcessorOption

func WithMaxQueueSize Uses

func WithMaxQueueSize(size int) BatchSpanProcessorOption

type BatchSpanProcessorOptions Uses

type BatchSpanProcessorOptions struct {
    // MaxQueueSize is the maximum queue size to buffer spans for delayed processing. If the
    // queue gets full it drops the spans. Use BlockOnQueueFull to change this behavior.
    // The default value of MaxQueueSize is 2048.
    MaxQueueSize int

    // BatchTimeout is the maximum duration for constructing a batch. Processor
    // forcefully sends available spans when timeout is reached.
    // The default value of BatchTimeout is 5000 msec.
    BatchTimeout time.Duration

    // MaxExportBatchSize is the maximum number of spans to process in a single batch.
    // If there are more than one batch worth of spans then it processes multiple batches
    // of spans one batch after the other without any delay.
    // The default value of MaxExportBatchSize is 512.
    MaxExportBatchSize int

    // BlockOnQueueFull blocks onEnd() and onStart() method if the queue is full
    // AND if BlockOnQueueFull is set to true.
    // Blocking option should be used carefully as it can severely affect the performance of an
    // application.
    BlockOnQueueFull bool

type Config Uses

type Config struct {
    // DefaultSampler is the default sampler used when creating new spans.
    DefaultSampler Sampler

    // IDGenerator is for internal use only.
    IDGenerator IDGenerator

    // MaxEventsPerSpan is max number of message events per span
    MaxEventsPerSpan int

    // MaxAnnotationEventsPerSpan is max number of attributes per span
    MaxAttributesPerSpan int

    // MaxLinksPerSpan is max number of links per span
    MaxLinksPerSpan int

    // Resource contains attributes representing an entity that produces telemetry.
    Resource *resource.Resource

Config represents the global tracing configuration.

type IDGenerator Uses

type IDGenerator interface {
    NewIDs(ctx context.Context) (trace.TraceID, trace.SpanID)
    NewSpanID(ctx context.Context, traceID trace.TraceID) trace.SpanID

IDGenerator allows custom generators for TraceID and SpanID.

type ParentBasedSamplerOption Uses

type ParentBasedSamplerOption interface {

ParentBasedSamplerOption configures the sampler for a particular sampling case.

func WithLocalParentNotSampled Uses

func WithLocalParentNotSampled(s Sampler) ParentBasedSamplerOption

WithLocalParentNotSampled sets the sampler for the case of local parent which is not sampled.

func WithLocalParentSampled Uses

func WithLocalParentSampled(s Sampler) ParentBasedSamplerOption

WithLocalParentSampled sets the sampler for the case of sampled local parent.

func WithRemoteParentNotSampled Uses

func WithRemoteParentNotSampled(s Sampler) ParentBasedSamplerOption

WithRemoteParentNotSampled sets the sampler for the case of remote parent which is not sampled.

func WithRemoteParentSampled Uses

func WithRemoteParentSampled(s Sampler) ParentBasedSamplerOption

WithRemoteParentSampled sets the sampler for the case of sampled remote parent.

type ReadOnlySpan Uses

type ReadOnlySpan interface {
    Name() string
    SpanContext() trace.SpanContext
    Parent() trace.SpanContext
    SpanKind() trace.SpanKind
    StartTime() time.Time
    EndTime() time.Time
    Attributes() []label.KeyValue
    Links() []trace.Link
    Events() []trace.Event
    StatusCode() codes.Code
    StatusMessage() string
    Tracer() trace.Tracer
    IsRecording() bool
    InstrumentationLibrary() instrumentation.Library
    Resource() *resource.Resource
    Snapshot() *export.SpanSnapshot

ReadOnlySpan allows reading information from the data structure underlying a trace.Span. It is used in places where reading information from a span is necessary but changing the span isn't necessary or allowed. TODO: Should we make the methods unexported? The purpose of this interface is controlling access to `span` fields, not having multiple implementations.

type ReadWriteSpan Uses

type ReadWriteSpan interface {

ReadWriteSpan exposes the same methods as trace.Span and in addition allows reading information from the underlying data structure. This interface exposes the union of the methods of trace.Span (which is a "write-only" span) and ReadOnlySpan. New methods for writing or reading span information should be added under trace.Span or ReadOnlySpan, respectively.

type Sampler Uses

type Sampler interface {
    ShouldSample(parameters SamplingParameters) SamplingResult
    Description() string

Sampler decides whether a trace should be sampled and exported.

func AlwaysSample Uses

func AlwaysSample() Sampler

AlwaysSample returns a Sampler that samples every trace. Be careful about using this sampler in a production application with significant traffic: a new trace will be started and exported for every request.

func NeverSample Uses

func NeverSample() Sampler

NeverSample returns a Sampler that samples no traces.

func ParentBased Uses

func ParentBased(root Sampler, samplers ...ParentBasedSamplerOption) Sampler

ParentBased returns a composite sampler which behaves differently, based on the parent of the span. If the span has no parent, the root(Sampler) is used to make sampling decision. If the span has a parent, depending on whether the parent is remote and whether it is sampled, one of the following samplers will apply: - remoteParentSampled(Sampler) (default: AlwaysOn) - remoteParentNotSampled(Sampler) (default: AlwaysOff) - localParentSampled(Sampler) (default: AlwaysOn) - localParentNotSampled(Sampler) (default: AlwaysOff)

func TraceIDRatioBased Uses

func TraceIDRatioBased(fraction float64) Sampler

TraceIDRatioBased samples a given fraction of traces. Fractions >= 1 will always sample. Fractions < 0 are treated as zero. To respect the parent trace's `SampledFlag`, the `TraceIDRatioBased` sampler should be used as a delegate of a `Parent` sampler.

type SamplingDecision Uses

type SamplingDecision uint8

SamplingDecision indicates whether a span is dropped, recorded and/or sampled.

const (
    // Drop will not record the span and all attributes/events will be dropped
    Drop SamplingDecision = iota

    // Record indicates the span's `IsRecording() == true`, but `Sampled` flag
    // *must not* be set

    // RecordAndSample has span's `IsRecording() == true` and `Sampled` flag
    // *must* be set

Valid sampling decisions

type SamplingParameters Uses

type SamplingParameters struct {
    ParentContext   trace.SpanContext
    TraceID         trace.TraceID
    Name            string
    HasRemoteParent bool
    Kind            trace.SpanKind
    Attributes      []label.KeyValue
    Links           []trace.Link

SamplingParameters contains the values passed to a Sampler.

type SamplingResult Uses

type SamplingResult struct {
    Decision   SamplingDecision
    Attributes []label.KeyValue
    Tracestate trace.TraceState

SamplingResult conveys a SamplingDecision, set of Attributes and a Tracestate.

type SimpleSpanProcessor Uses

type SimpleSpanProcessor struct {
    // contains filtered or unexported fields

SimpleSpanProcessor is a SpanProcessor that synchronously sends all SpanSnapshots to a trace.Exporter when the span finishes.

func NewSimpleSpanProcessor Uses

func NewSimpleSpanProcessor(exporter export.SpanExporter) *SimpleSpanProcessor

NewSimpleSpanProcessor returns a new SimpleSpanProcessor that will synchronously send SpanSnapshots to the exporter.

func (*SimpleSpanProcessor) ForceFlush Uses

func (ssp *SimpleSpanProcessor) ForceFlush()

ForceFlush does nothing as there is no data to flush.

func (*SimpleSpanProcessor) OnEnd Uses

func (ssp *SimpleSpanProcessor) OnEnd(s ReadOnlySpan)

OnEnd method exports a ReadOnlySpan using the associated exporter.

func (*SimpleSpanProcessor) OnStart Uses

func (ssp *SimpleSpanProcessor) OnStart(parent context.Context, s ReadWriteSpan)

OnStart method does nothing.

func (*SimpleSpanProcessor) Shutdown Uses

func (ssp *SimpleSpanProcessor) Shutdown(_ context.Context) error

Shutdown method does nothing. There is no data to cleanup.

type SpanProcessor Uses

type SpanProcessor interface {

    // OnStart method is invoked when span is started. It is a synchronous call
    // and hence should not block.
    OnStart(parent context.Context, s ReadWriteSpan)

    // OnEnd method is invoked when span is finished. It is a synchronous call
    // and hence should not block.
    OnEnd(s ReadOnlySpan)

    // Shutdown is invoked when SDK shuts down. Use this call to cleanup any processor
    // data. No calls to OnStart and OnEnd method is invoked after Shutdown call is
    // made. It should not be blocked indefinitely.
    Shutdown(ctx context.Context) error

    // ForceFlush exports all ended spans to the configured Exporter that have not yet
    // been exported.  It should only be called when absolutely necessary, such as when
    // using a FaaS provider that may suspend the process after an invocation, but before
    // the Processor can export the completed spans.

SpanProcessor is interface to add hooks to start and end method invocations.


package main

import (


// DurationFilter is a SpanProcessor that filters spans that have lifetimes
// outside of a defined range.
type DurationFilter struct {
    // Next is the next SpanProcessor in the chain.
    Next SpanProcessor

    // Min is the duration under which spans are dropped.
    Min time.Duration
    // Max is the duration over which spans are dropped.
    Max time.Duration

func (f DurationFilter) OnStart(parent context.Context, s ReadWriteSpan) {
    f.Next.OnStart(parent, s)
func (f DurationFilter) Shutdown(ctx context.Context) error { return f.Next.Shutdown(ctx) }
func (f DurationFilter) ForceFlush()                        { f.Next.ForceFlush() }
func (f DurationFilter) OnEnd(s ReadOnlySpan) {
    if f.Min > 0 && s.EndTime().Sub(s.StartTime()) < f.Min {
        // Drop short lived spans.
    if f.Max > 0 && s.EndTime().Sub(s.StartTime()) > f.Max {
        // Drop long lived spans.

// InstrumentationBlacklist is a SpanProcessor that drops all spans from
// certain instrumentation.
type InstrumentationBlacklist struct {
    // Next is the next SpanProcessor in the chain.
    Next SpanProcessor

    // Blacklist is the set of instrumentation names for which spans will be
    // dropped.
    Blacklist map[string]bool

func (f InstrumentationBlacklist) OnStart(parent context.Context, s ReadWriteSpan) {
    f.Next.OnStart(parent, s)
func (f InstrumentationBlacklist) Shutdown(ctx context.Context) error { return f.Next.Shutdown(ctx) }
func (f InstrumentationBlacklist) ForceFlush()                        { f.Next.ForceFlush() }
func (f InstrumentationBlacklist) OnEnd(s ReadOnlySpan) {
    if f.Blacklist != nil && f.Blacklist[s.InstrumentationLibrary().Name] {
        // Drop spans from this instrumentation

func main() {
    exportSP := NewSimpleSpanProcessor(tracetest.NewNoopExporter())

    // Build a SpanProcessor chain to filter out all spans from the pernicious
    // "naughty-instrumentation" dependency and only allow spans shorter than
    // an minute and longer than a second to be exported with the exportSP.
    filter := DurationFilter{
        Next: InstrumentationBlacklist{
            Next: exportSP,
            Blacklist: map[string]bool{
                "naughty-instrumentation": true,
        Min: time.Second,
        Max: time.Minute,

    _ = NewTracerProvider(WithSpanProcessor(filter))
    // ...

type TracerProvider Uses

type TracerProvider struct {
    // contains filtered or unexported fields

func NewTracerProvider Uses

func NewTracerProvider(opts ...TracerProviderOption) *TracerProvider

NewTracerProvider creates an instance of trace provider. Optional parameter configures the provider with common options applicable to all tracer instances that will be created by this provider.

func (*TracerProvider) ApplyConfig Uses

func (p *TracerProvider) ApplyConfig(cfg Config)

ApplyConfig changes the configuration of the provider. If a field in the configuration is empty or nil then its original value is preserved.

func (*TracerProvider) RegisterSpanProcessor Uses

func (p *TracerProvider) RegisterSpanProcessor(s SpanProcessor)

RegisterSpanProcessor adds the given SpanProcessor to the list of SpanProcessors

func (*TracerProvider) Shutdown Uses

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

Shutdown shuts down the span processors in the order they were registered

func (*TracerProvider) Tracer Uses

func (p *TracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.Tracer

Tracer with the given name. If a tracer for the given name does not exist, it is created first. If the name is empty, DefaultTracerName is used.

func (*TracerProvider) UnregisterSpanProcessor Uses

func (p *TracerProvider) UnregisterSpanProcessor(s SpanProcessor)

UnregisterSpanProcessor removes the given SpanProcessor from the list of SpanProcessors

type TracerProviderConfig Uses

type TracerProviderConfig struct {
    // contains filtered or unexported fields


type TracerProviderOption Uses

type TracerProviderOption func(*TracerProviderConfig)

func WithBatcher Uses

func WithBatcher(e export.SpanExporter, opts ...BatchSpanProcessorOption) TracerProviderOption

WithBatcher registers the exporter with the TracerProvider using a BatchSpanProcessor configured with the passed opts.

func WithConfig Uses

func WithConfig(config Config) TracerProviderOption

WithConfig option sets the configuration to provider.

func WithIDGenerator Uses

func WithIDGenerator(g IDGenerator) TracerProviderOption

WithIDGenerator option registers an IDGenerator with the TracerProvider.

func WithResource Uses

func WithResource(r *resource.Resource) TracerProviderOption

WithResource option attaches a resource to the provider. The resource is added to the span when it is started.

func WithSpanProcessor Uses

func WithSpanProcessor(sp SpanProcessor) TracerProviderOption

WithSpanProcessor registers the SpanProcessor with a TracerProvider.

func WithSyncer Uses

func WithSyncer(e export.SpanExporter) TracerProviderOption

WithSyncer registers the exporter with the TracerProvider using a SimpleSpanProcessor.

Package trace imports 21 packages (graph) and is imported by 50 packages. Updated 2021-01-16. Refresh now. Tools for package owners.