Documentation

Overview

Package trace contains support for OpenCensus distributed tracing.

The following assumes a basic familiarity with OpenCensus concepts. See http://opencensus.io

Exporting Traces

To export collected tracing data, register at least one exporter. You can use one of the provided exporters or write your own.

trace.RegisterExporter(exporter)

By default, traces will be sampled relatively rarely. To change the sampling frequency for your entire program, call ApplyConfig. Use a ProbabilitySampler to sample a subset of traces, or use AlwaysSample to collect a trace on every run:

trace.ApplyConfig(trace.Config{DefaultSampler: trace.AlwaysSample()})

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

Adding Spans to a Trace

A trace consists of a tree of spans. In Go, the current span is carried in a context.Context.

It is common to want to capture all the activity of a function call in a span. For this to work, the function must take a context.Context as a parameter. Add these two lines to the top of the function:

ctx, span := trace.StartSpan(ctx, "example.com/Run")
defer span.End()

StartSpan will create a new top-level span if the context doesn't contain another span, otherwise it will create a child span.

Index

Examples

Constants

View Source
const (
	// DefaultMaxAnnotationEventsPerSpan is default max number of annotation events per span
	DefaultMaxAnnotationEventsPerSpan = 32

	// DefaultMaxMessageEventsPerSpan is default max number of message events per span
	DefaultMaxMessageEventsPerSpan = 128

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

	// DefaultMaxLinksPerSpan is default max number of links per span
	DefaultMaxLinksPerSpan = 32
)
View Source
const (
	StatusCodeOK                 = 0
	StatusCodeCancelled          = 1
	StatusCodeUnknown            = 2
	StatusCodeInvalidArgument    = 3
	StatusCodeDeadlineExceeded   = 4
	StatusCodeNotFound           = 5
	StatusCodeAlreadyExists      = 6
	StatusCodePermissionDenied   = 7
	StatusCodeResourceExhausted  = 8
	StatusCodeFailedPrecondition = 9
	StatusCodeAborted            = 10
	StatusCodeOutOfRange         = 11
	StatusCodeUnimplemented      = 12
	StatusCodeInternal           = 13
	StatusCodeUnavailable        = 14
	StatusCodeDataLoss           = 15
	StatusCodeUnauthenticated    = 16
)

    Status codes for use with Span.SetStatus. These correspond to the status codes used by gRPC defined here: https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto

    View Source
    const (
    	SpanKindUnspecified = iota
    	SpanKindServer
    	SpanKindClient
    )

      All available span kinds. Span kind must be either one of these values.

      Variables

      This section is empty.

      Functions

      func ApplyConfig

      func ApplyConfig(cfg Config)

        ApplyConfig applies changes to the global tracing configuration.

        Fields not provided in the given config are going to be preserved.

        func NewContext

        func NewContext(parent context.Context, s *Span) context.Context

          NewContext returns a new context with the given Span attached.

          func RegisterExporter

          func RegisterExporter(e Exporter)

            RegisterExporter adds to the list of Exporters that will receive sampled trace spans.

            Binaries can register exporters, libraries shouldn't register exporters.

            func UnregisterExporter

            func UnregisterExporter(e Exporter)

              UnregisterExporter removes from the list of Exporters the Exporter that was registered with the given name.

              Types

              type Annotation

              type Annotation struct {
              	Time       time.Time
              	Message    string
              	Attributes map[string]interface{}
              }

                Annotation represents a text annotation with a set of attributes and a timestamp.

                type Attribute

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

                  Attribute represents a key-value pair on a span, link or annotation. Construct with one of: BoolAttribute, Int64Attribute, or StringAttribute.

                  func BoolAttribute

                  func BoolAttribute(key string, value bool) Attribute

                    BoolAttribute returns a bool-valued attribute.

                    func Float64Attribute

                    func Float64Attribute(key string, value float64) Attribute

                      Float64Attribute returns a float64-valued attribute.

                      func Int64Attribute

                      func Int64Attribute(key string, value int64) Attribute

                        Int64Attribute returns an int64-valued attribute.

                        func StringAttribute

                        func StringAttribute(key string, value string) Attribute

                          StringAttribute returns a string-valued attribute.

                          func (*Attribute) Key

                          func (a *Attribute) Key() string

                            Key returns the attribute's key

                            func (*Attribute) Value

                            func (a *Attribute) Value() interface{}

                              Value returns the attribute's value

                              type Config

                              type Config struct {
                              	// DefaultSampler is the default sampler used when creating new spans.
                              	DefaultSampler Sampler
                              
                              	// IDGenerator is for internal use only.
                              	IDGenerator internal.IDGenerator
                              
                              	// MaxAnnotationEventsPerSpan is max number of annotation events per span
                              	MaxAnnotationEventsPerSpan int
                              
                              	// MaxMessageEventsPerSpan is max number of message events per span
                              	MaxMessageEventsPerSpan int
                              
                              	// MaxAnnotationEventsPerSpan is max number of attributes per span
                              	MaxAttributesPerSpan int
                              
                              	// MaxLinksPerSpan is max number of links per span
                              	MaxLinksPerSpan int
                              }

                                Config represents the global tracing configuration.

                                type Exporter

                                type Exporter interface {
                                	ExportSpan(s *SpanData)
                                }

                                  Exporter is a type for functions that receive sampled trace spans.

                                  The ExportSpan method should be safe for concurrent use and should return quickly; if an Exporter takes a significant amount of time to process a SpanData, that work should be done on another goroutine.

                                  The SpanData should not be modified, but a pointer to it can be kept.

                                  type Link struct {
                                  	TraceID TraceID
                                  	SpanID  SpanID
                                  	Type    LinkType
                                  	// Attributes is a set of attributes on the link.
                                  	Attributes map[string]interface{}
                                  }

                                    Link represents a reference from one span to another span.

                                    type LinkType

                                    type LinkType int32

                                      LinkType specifies the relationship between the span that had the link added, and the linked span.

                                      const (
                                      	LinkTypeUnspecified LinkType = iota // The relationship of the two spans is unknown.
                                      	LinkTypeChild                       // The linked span is a child of the current span.
                                      	LinkTypeParent                      // The linked span is the parent of the current span.
                                      )

                                        LinkType values.

                                        type MessageEvent

                                        type MessageEvent struct {
                                        	Time                 time.Time
                                        	EventType            MessageEventType
                                        	MessageID            int64
                                        	UncompressedByteSize int64
                                        	CompressedByteSize   int64
                                        }

                                          MessageEvent represents an event describing a message sent or received on the network.

                                          type MessageEventType

                                          type MessageEventType int32

                                            MessageEventType specifies the type of message event.

                                            const (
                                            	MessageEventTypeUnspecified MessageEventType = iota // Unknown event type.
                                            	MessageEventTypeSent                                // Indicates a sent RPC message.
                                            	MessageEventTypeRecv                                // Indicates a received RPC message.
                                            )

                                              MessageEventType values.

                                              type Sampler

                                                Sampler decides whether a trace should be sampled and exported.

                                                func AlwaysSample

                                                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

                                                  func NeverSample() Sampler

                                                    NeverSample returns a Sampler that samples no traces.

                                                    func ProbabilitySampler

                                                    func ProbabilitySampler(fraction float64) Sampler

                                                      ProbabilitySampler returns a Sampler that samples a given fraction of traces.

                                                      It also samples spans whose parents are sampled.

                                                      type SamplingDecision

                                                      type SamplingDecision struct {
                                                      	Sample bool
                                                      }

                                                        SamplingDecision is the value returned by a Sampler.

                                                        type SamplingParameters

                                                        type SamplingParameters struct {
                                                        	ParentContext   SpanContext
                                                        	TraceID         TraceID
                                                        	SpanID          SpanID
                                                        	Name            string
                                                        	HasRemoteParent bool
                                                        }

                                                          SamplingParameters contains the values passed to a Sampler.

                                                          type Span

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

                                                            Span is a struct wrapper around the SpanInt interface, which allows correctly handling nil spans, while also allowing the SpanInterface implementation to be swapped out.

                                                            func FromContext

                                                            func FromContext(ctx context.Context) *Span

                                                              FromContext returns the Span stored in a context, or a Span that is not recording events if there isn't one.

                                                              func NewSpan

                                                              func NewSpan(s SpanInterface) *Span

                                                                NewSpan is a convenience function for creating a *Span out of a *span

                                                                func StartSpan

                                                                func StartSpan(ctx context.Context, name string, o ...StartOption) (context.Context, *Span)

                                                                  StartSpan starts a new child span of the current span in the context. If there is no span in the context, creates a new trace and span.

                                                                  Returned context contains the newly created span. You can use it to propagate the returned span in process.

                                                                  Example

                                                                    This example shows how to use StartSpan and (*Span).End to capture a function execution in a Span. It assumes that the function has a context.Context argument.

                                                                    Output:
                                                                    
                                                                    

                                                                    func StartSpanWithRemoteParent

                                                                    func StartSpanWithRemoteParent(ctx context.Context, name string, parent SpanContext, o ...StartOption) (context.Context, *Span)

                                                                      StartSpanWithRemoteParent starts a new child span of the span from the given parent.

                                                                      If the incoming context contains a parent, it ignores. StartSpanWithRemoteParent is preferred for cases where the parent is propagated via an incoming request.

                                                                      Returned context contains the newly created span. You can use it to propagate the returned span in process.

                                                                      func (*Span) AddAttributes

                                                                      func (s *Span) AddAttributes(attributes ...Attribute)

                                                                        AddAttributes sets attributes in the span.

                                                                        Existing attributes whose keys appear in the attributes parameter are overwritten.

                                                                        func (s *Span) AddLink(l Link)

                                                                          AddLink adds a link to the span.

                                                                          func (*Span) AddMessageReceiveEvent

                                                                          func (s *Span) AddMessageReceiveEvent(messageID, uncompressedByteSize, compressedByteSize int64)

                                                                            AddMessageReceiveEvent adds a message receive event to the span.

                                                                            messageID is an identifier for the message, which is recommended to be unique in this span and the same between the send event and the receive event (this allows to identify a message between the sender and receiver). For example, this could be a sequence id.

                                                                            func (*Span) AddMessageSendEvent

                                                                            func (s *Span) AddMessageSendEvent(messageID, uncompressedByteSize, compressedByteSize int64)

                                                                              AddMessageSendEvent adds a message send event to the span.

                                                                              messageID is an identifier for the message, which is recommended to be unique in this span and the same between the send event and the receive event (this allows to identify a message between the sender and receiver). For example, this could be a sequence id.

                                                                              func (*Span) Annotate

                                                                              func (s *Span) Annotate(attributes []Attribute, str string)

                                                                                Annotate adds an annotation with attributes. Attributes can be nil.

                                                                                func (*Span) Annotatef

                                                                                func (s *Span) Annotatef(attributes []Attribute, format string, a ...interface{})

                                                                                  Annotatef adds an annotation with attributes.

                                                                                  func (*Span) End

                                                                                  func (s *Span) End()

                                                                                    End ends the span.

                                                                                    func (*Span) Internal

                                                                                    func (s *Span) Internal() SpanInterface

                                                                                      Internal returns the underlying implementation of the Span

                                                                                      func (*Span) IsRecordingEvents

                                                                                      func (s *Span) IsRecordingEvents() bool

                                                                                        IsRecordingEvents returns true if events are being recorded for this span. Use this check to avoid computing expensive annotations when they will never be used.

                                                                                        func (*Span) SetName

                                                                                        func (s *Span) SetName(name string)

                                                                                          SetName sets the name of the span, if it is recording events.

                                                                                          func (*Span) SetStatus

                                                                                          func (s *Span) SetStatus(status Status)

                                                                                            SetStatus sets the status of the span, if it is recording events.

                                                                                            func (*Span) SpanContext

                                                                                            func (s *Span) SpanContext() SpanContext

                                                                                              SpanContext returns the SpanContext of the span.

                                                                                              func (*Span) String

                                                                                              func (s *Span) String() string

                                                                                                String prints a string representation of a span.

                                                                                                type SpanContext

                                                                                                type SpanContext struct {
                                                                                                	TraceID      TraceID
                                                                                                	SpanID       SpanID
                                                                                                	TraceOptions TraceOptions
                                                                                                	Tracestate   *tracestate.Tracestate
                                                                                                }

                                                                                                  SpanContext contains the state that must propagate across process boundaries.

                                                                                                  SpanContext is not an implementation of context.Context. TODO: add reference to external Census docs for SpanContext.

                                                                                                  func (SpanContext) IsSampled

                                                                                                  func (sc SpanContext) IsSampled() bool

                                                                                                    IsSampled returns true if the span will be exported.

                                                                                                    type SpanData

                                                                                                    type SpanData struct {
                                                                                                    	SpanContext
                                                                                                    	ParentSpanID SpanID
                                                                                                    	SpanKind     int
                                                                                                    	Name         string
                                                                                                    	StartTime    time.Time
                                                                                                    	// The wall clock time of EndTime will be adjusted to always be offset
                                                                                                    	// from StartTime by the duration of the span.
                                                                                                    	EndTime time.Time
                                                                                                    	// The values of Attributes each have type string, bool, or int64.
                                                                                                    	Attributes    map[string]interface{}
                                                                                                    	Annotations   []Annotation
                                                                                                    	MessageEvents []MessageEvent
                                                                                                    	Status
                                                                                                    	Links                    []Link
                                                                                                    	HasRemoteParent          bool
                                                                                                    	DroppedAttributeCount    int
                                                                                                    	DroppedAnnotationCount   int
                                                                                                    	DroppedMessageEventCount int
                                                                                                    	DroppedLinkCount         int
                                                                                                    
                                                                                                    	// ChildSpanCount holds the number of child span created for this span.
                                                                                                    	ChildSpanCount int
                                                                                                    }

                                                                                                      SpanData contains all the information collected by a Span.

                                                                                                      type SpanID

                                                                                                      type SpanID [8]byte

                                                                                                        SpanID is an 8-byte identifier for a single span.

                                                                                                        func (SpanID) String

                                                                                                        func (s SpanID) String() string

                                                                                                        type SpanInterface

                                                                                                        type SpanInterface interface {
                                                                                                        
                                                                                                        	// IsRecordingEvents returns true if events are being recorded for this span.
                                                                                                        	// Use this check to avoid computing expensive annotations when they will never
                                                                                                        	// be used.
                                                                                                        	IsRecordingEvents() bool
                                                                                                        
                                                                                                        	// End ends the span.
                                                                                                        	End()
                                                                                                        
                                                                                                        	// SpanContext returns the SpanContext of the span.
                                                                                                        	SpanContext() SpanContext
                                                                                                        
                                                                                                        	// SetName sets the name of the span, if it is recording events.
                                                                                                        	SetName(name string)
                                                                                                        
                                                                                                        	// SetStatus sets the status of the span, if it is recording events.
                                                                                                        	SetStatus(status Status)
                                                                                                        
                                                                                                        	// AddAttributes sets attributes in the span.
                                                                                                        	//
                                                                                                        	// Existing attributes whose keys appear in the attributes parameter are overwritten.
                                                                                                        	AddAttributes(attributes ...Attribute)
                                                                                                        
                                                                                                        	// Annotate adds an annotation with attributes.
                                                                                                        	// Attributes can be nil.
                                                                                                        	Annotate(attributes []Attribute, str string)
                                                                                                        
                                                                                                        	// Annotatef adds an annotation with attributes.
                                                                                                        	Annotatef(attributes []Attribute, format string, a ...interface{})
                                                                                                        
                                                                                                        	// AddMessageSendEvent adds a message send event to the span.
                                                                                                        	//
                                                                                                        	// messageID is an identifier for the message, which is recommended to be
                                                                                                        	// unique in this span and the same between the send event and the receive
                                                                                                        	// event (this allows to identify a message between the sender and receiver).
                                                                                                        	// For example, this could be a sequence id.
                                                                                                        	AddMessageSendEvent(messageID, uncompressedByteSize, compressedByteSize int64)
                                                                                                        
                                                                                                        	// AddMessageReceiveEvent adds a message receive event to the span.
                                                                                                        	//
                                                                                                        	// messageID is an identifier for the message, which is recommended to be
                                                                                                        	// unique in this span and the same between the send event and the receive
                                                                                                        	// event (this allows to identify a message between the sender and receiver).
                                                                                                        	// For example, this could be a sequence id.
                                                                                                        	AddMessageReceiveEvent(messageID, uncompressedByteSize, compressedByteSize int64)
                                                                                                        
                                                                                                        	// AddLink adds a link to the span.
                                                                                                        	AddLink(l Link)
                                                                                                        
                                                                                                        	// String prints a string representation of a span.
                                                                                                        	String() string
                                                                                                        }

                                                                                                          SpanInterface represents a span of a trace. It has an associated SpanContext, and stores data accumulated while the span is active.

                                                                                                          Ideally users should interact with Spans by calling the functions in this package that take a Context parameter.

                                                                                                          type StartOption

                                                                                                          type StartOption func(*StartOptions)

                                                                                                            StartOption apply changes to StartOptions.

                                                                                                            func WithSampler

                                                                                                            func WithSampler(sampler Sampler) StartOption

                                                                                                              WithSampler makes new spans to be be created with a custom sampler. Otherwise, the global sampler is used.

                                                                                                              func WithSpanKind

                                                                                                              func WithSpanKind(spanKind int) StartOption

                                                                                                                WithSpanKind makes new spans to be created with the given kind.

                                                                                                                type StartOptions

                                                                                                                type StartOptions struct {
                                                                                                                	// Sampler to consult for this Span. If provided, it is always consulted.
                                                                                                                	//
                                                                                                                	// If not provided, then the behavior differs based on whether
                                                                                                                	// the parent of this Span is remote, local, or there is no parent.
                                                                                                                	// In the case of a remote parent or no parent, the
                                                                                                                	// default sampler (see Config) will be consulted. Otherwise,
                                                                                                                	// when there is a non-remote parent, no new sampling decision will be made:
                                                                                                                	// we will preserve the sampling of the parent.
                                                                                                                	Sampler Sampler
                                                                                                                
                                                                                                                	// SpanKind represents the kind of a span. If none is set,
                                                                                                                	// SpanKindUnspecified is used.
                                                                                                                	SpanKind int
                                                                                                                }

                                                                                                                  StartOptions contains options concerning how a span is started.

                                                                                                                  type Status

                                                                                                                  type Status struct {
                                                                                                                  	// Code is a status code.  Zero indicates success.
                                                                                                                  	//
                                                                                                                  	// If Code will be propagated to Google APIs, it ideally should be a value from
                                                                                                                  	// https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto .
                                                                                                                  	Code    int32
                                                                                                                  	Message string
                                                                                                                  }

                                                                                                                    Status is the status of a Span.

                                                                                                                    type TraceID

                                                                                                                    type TraceID [16]byte

                                                                                                                      TraceID is a 16-byte identifier for a set of spans.

                                                                                                                      func (TraceID) String

                                                                                                                      func (t TraceID) String() string

                                                                                                                      type TraceOptions

                                                                                                                      type TraceOptions uint32

                                                                                                                        TraceOptions contains options associated with a trace span.

                                                                                                                        func (TraceOptions) IsSampled

                                                                                                                        func (t TraceOptions) IsSampled() bool

                                                                                                                          IsSampled returns true if the span will be exported.

                                                                                                                          type Tracer

                                                                                                                          type Tracer interface {
                                                                                                                          
                                                                                                                          	// StartSpan starts a new child span of the current span in the context. If
                                                                                                                          	// there is no span in the context, creates a new trace and span.
                                                                                                                          	//
                                                                                                                          	// Returned context contains the newly created span. You can use it to
                                                                                                                          	// propagate the returned span in process.
                                                                                                                          	StartSpan(ctx context.Context, name string, o ...StartOption) (context.Context, *Span)
                                                                                                                          
                                                                                                                          	// StartSpanWithRemoteParent starts a new child span of the span from the given parent.
                                                                                                                          	//
                                                                                                                          	// If the incoming context contains a parent, it ignores. StartSpanWithRemoteParent is
                                                                                                                          	// preferred for cases where the parent is propagated via an incoming request.
                                                                                                                          	//
                                                                                                                          	// Returned context contains the newly created span. You can use it to
                                                                                                                          	// propagate the returned span in process.
                                                                                                                          	StartSpanWithRemoteParent(ctx context.Context, name string, parent SpanContext, o ...StartOption) (context.Context, *Span)
                                                                                                                          
                                                                                                                          	// FromContext returns the Span stored in a context, or nil if there isn't one.
                                                                                                                          	FromContext(ctx context.Context) *Span
                                                                                                                          
                                                                                                                          	// NewContext returns a new context with the given Span attached.
                                                                                                                          	NewContext(parent context.Context, s *Span) context.Context
                                                                                                                          }

                                                                                                                            Tracer can start spans and access context functions.

                                                                                                                            var DefaultTracer Tracer = &tracer{}

                                                                                                                              DefaultTracer is the tracer used when package-level exported functions are invoked.

                                                                                                                              Directories

                                                                                                                              Path Synopsis
                                                                                                                              Package propagation implements the binary trace context format.
                                                                                                                              Package propagation implements the binary trace context format.
                                                                                                                              Package tracestate implements support for the Tracestate header of the W3C TraceContext propagation format.
                                                                                                                              Package tracestate implements support for the Tracestate header of the W3C TraceContext propagation format.
                                                                                                                              Package internal provides trace internals.
                                                                                                                              Package internal provides trace internals.