Involved Source Filesbasetypes.goconfig.go
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.
evictedqueue.goexport.golrumap.gosampling.gospanbucket.gospanstore.gostatus_codes.gotrace.gotrace_go11.go
Package-Level Type Names (total 28, in which 20 are exported)
Config represents the global tracing configuration.
DefaultSampler is the default sampler used when creating new spans.
IDGenerator is for internal use only.
MaxAnnotationEventsPerSpan is max number of annotation events per span
MaxAnnotationEventsPerSpan is max number of attributes per span
MaxLinksPerSpan is max number of links per span
MaxMessageEventsPerSpan is max number of message events per span
func ApplyConfig(cfg Config)
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.
( T) ExportSpan(s *SpanData)
*contrib.go.opencensus.io/exporter/stackdriver.Exporter
*contrib.go.opencensus.io/exporter/stackdriver.traceExporter
*golang.org/x/pkgsite/internal/dcensus.debugTraceExporter
func RegisterExporter(e Exporter)
func UnregisterExporter(e Exporter)
Span 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.
annotations are stored in FIFO queue capped by configured limit.
data contains information recorded about the span.
It will be non-nil if we are exporting the span or recording events for it.
Otherwise, data is nil, and the Span is simply a carrier for the
SpanContext, so that the trace ID is propagated.
endOncesync.Once
// ends the execution tracer span
links are stored in FIFO queue capped by configured limit.
lruAttributes are capped at configured limit. When the capacity is reached an oldest entry
is removed to create room for a new entry.
messageEvents are stored in FIFO queue capped by configured limit.
// protects the contents of *data (but not the pointer value.)
spanContextSpanContext
spanStore is the spanStore this span belongs to, if any, otherwise it is nil.
spanStore.activemap[*Span]struct{}spanStore.errorsmap[int32]*bucketspanStore.latency[]bucketspanStore.maxSpansPerErrorBucketint
AddAttributes sets attributes in the span.
Existing attributes whose keys appear in the attributes parameter are overwritten.
AddLink adds a link to the span.
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.
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.
Annotate adds an annotation with attributes.
Attributes can be nil.
Annotatef adds an annotation with attributes.
End ends the span.
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.
SetName sets the name of the span, if it is recording events.
SetStatus sets the status of the span, if it is recording events.
SpanContext returns the SpanContext of the span.
(*T) String() string
add adds a span to the active bucket of the spanStore.
(*T) addChild()(*T) copyToCappedAttributes(attributes []Attribute)
finished removes a span from the active set, and adds a corresponding
SpanData to a latency or error bucket.
(*T) interfaceArrayToAnnotationArray() []Annotation(*T) interfaceArrayToLinksArray() []Link(*T) interfaceArrayToMessageEventArray() []MessageEvent(*T) lazyPrintfInternal(attributes []Attribute, format string, a ...interface{})(*T) lruAttributesToAttributeMap() map[string]interface{}
makeSpanData produces a SpanData representing the current state of the Span.
It requires that s.data is non-nil.
(*T) printStringInternal(attributes []Attribute, str string)( T) resize(latencyBucketSize int, errorBucketSize int)
*T : expvar.Var
*T : fmt.Stringer
*T : context.stringer
*T : runtime.stringer
func FromContext(ctx context.Context) *Span
func StartSpan(ctx context.Context, name string, o ...StartOption) (context.Context, *Span)
func StartSpanWithRemoteParent(ctx context.Context, name string, parent SpanContext, o ...StartOption) (context.Context, *Span)
func startSpanInternal(name string, hasParent bool, parent SpanContext, remoteParent bool, o StartOptions) *Span
func NewContext(parent context.Context, s *Span) context.Context
func go.opencensus.io/plugin/ochttp.NewSpanAnnotatingClientTrace(_ *http.Request, s *Span) *httptrace.ClientTrace
func go.opencensus.io/plugin/ochttp.NewSpanAnnotator(r *http.Request, s *Span) *httptrace.ClientTrace
func contrib.go.opencensus.io/integrations/ocsql.setSpanStatus(span *Span, err error)
SpanID is an 8-byte identifier for a single span.
( T) String() string
T : expvar.Var
T : fmt.Stringer
T : context.stringer
T : runtime.stringer
func go.opencensus.io/plugin/ochttp/propagation/b3.ParseSpanID(sid string) (spanID SpanID, ok bool)
StartOptions contains options concerning how a span is started.
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.
SpanKind represents the kind of a span. If none is set,
SpanKindUnspecified is used.
func startSpanInternal(name string, hasParent bool, parent SpanContext, remoteParent bool, o StartOptions) *Span
Status is the status of a Span.
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 .
Messagestring
func go.opencensus.io/plugin/ochttp.TraceStatus(httpStatusCode int, statusLine string) Status
func cloud.google.com/go/internal/trace.toStatus(err error) Status
func (*Span).SetStatus(status Status)
TraceOptions contains options associated with a trace span.
IsSampled returns true if the span will be exported.
func go.opencensus.io/plugin/ochttp/propagation/b3.ParseSampled(sampled string) (TraceOptions, bool)
bucket is a container for a set of spans for a particular error code or latency range.
// circular buffer of spans
// location next SpanData should be placed in buffer
// next time we can accept a span
// whether the circular buffer has wrapped around
add adds a span to the bucket, if nextTime has been reached.
resize changes the size of the bucket to n, keeping up to n existing spans.
size returns the number of spans in the bucket.
span returns the ith span in the bucket.
func makeBucket(bufferSize int) bucket
Mutexsync.MutexMutex.semauint32Mutex.stateint32
Please keep these as the first fields
so that these 8 byte fields will be aligned on addresses
divisible by 8, on both 32-bit and 64-bit machines when
performing atomic increments and accesses.
See:
* https://github.com/census-instrumentation/opencensus-go/issues/587
* https://github.com/census-instrumentation/opencensus-go/issues/865
* https://golang.org/pkg/sync/atomic/#pkg-note-BUG
spanIDIncuint64traceIDAdd[2]uint64traceIDRand*rand.Rand
Lock locks m.
If the lock is already in use, the calling goroutine
blocks until the mutex is available.
NewSpanID returns a non-zero span ID from a randomly-chosen sequence.
NewTraceID returns a non-zero trace ID from a randomly-chosen sequence.
mu should be held while this function is called.
Unlock unlocks m.
It is a run-time error if m is not locked on entry to Unlock.
A locked Mutex is not associated with a particular goroutine.
It is allowed for one goroutine to lock a Mutex and then
arrange for another goroutine to unlock it.
(*T) lockSlow()(*T) unlockSlow(new int32)
*T : go.opencensus.io/trace/internal.IDGenerator
*T : sync.Locker
This exists purely to avoid exposing internal methods used by z-Pages externally.
ConfigureBucketSizes sets the number of spans to keep per latency and error
bucket for different span names.
ReportActiveSpans returns the active spans for the given name.
ReportSpansByError returns a sample of error spans.
If code is nonzero, only spans with that status code are returned.
ReportSpansByLatency returns a sample of successful spans.
minLatency is the minimum latency of spans to be returned.
maxLatency, if nonzero, is the maximum latency of spans to be returned.
ReportSpansPerMethod returns a summary of what spans are being stored for each span name.
A simple lru.Cache wrapper that tracks the keys of the current contents and
the cumulative number of evicted items.
cache*lru.CachecacheKeysmap[lru.Key]booldroppedCountint(*T) add(key, value interface{})(*T) get(key interface{}) (interface{}, bool)( T) keys() []interface{}( T) len() int
func newLruMap(size int) *lruMap
spanStore keeps track of spans stored for a particular span name.
It contains all active spans; a sample of spans for failed requests,
categorized by error code; and a sample of spans for successful requests,
bucketed by latency.
activemap[*Span]struct{}errorsmap[int32]*bucketlatency[]bucketmaxSpansPerErrorBucketint
// protects everything below.
add adds a span to the active bucket of the spanStore.
finished removes a span from the active set, and adds a corresponding
SpanData to a latency or error bucket.
(*T) resize(latencyBucketSize int, errorBucketSize int)
func newSpanStore(name string, latencyBucketSize int, errorBucketSize int) *spanStore
func spanStoreForName(name string) *spanStore
func spanStoreForNameCreateIfNew(name string) *spanStore
Package-Level Functions (total 30, in which 16 are exported)
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.
ApplyConfig applies changes to the global tracing configuration.
Fields not provided in the given config are going to be preserved.
BoolAttribute returns a bool-valued attribute.
Float64Attribute returns a float64-valued attribute.
FromContext returns the Span stored in a context, or nil if there isn't one.
Int64Attribute returns an int64-valued attribute.
NeverSample returns a Sampler that samples no traces.
NewContext returns a new context with the given Span attached.
ProbabilitySampler returns a Sampler that samples a given fraction of traces.
It also samples spans whose parents are sampled.
RegisterExporter adds to the list of Exporters that will receive sampled
trace spans.
Binaries can register exporters, libraries shouldn't register exporters.
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.
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.
StringAttribute returns a string-valued attribute.
UnregisterExporter removes from the list of Exporters the Exporter that was
registered with the given name.
WithSampler makes new spans to be be created with a custom sampler.
Otherwise, the global sampler is used.
WithSpanKind makes new spans to be created with the given kind.
copyAttributes copies a slice of Attributes into a map.
latencyBucket returns the appropriate bucket number for a given latency.
latencyBucketBounds returns the lower and upper bounds for a latency bucket
number.
The lower bound is inclusive, the upper bound is exclusive (except for the
last bucket.)
Package-Level Constants (total 34, in which 30 are exported)
DefaultMaxAnnotationEventsPerSpan is default max number of annotation events per span
DefaultMaxAttributesPerSpan is default max number of attributes per span
DefaultMaxLinksPerSpan is default max number of links per span
DefaultMaxMessageEventsPerSpan is default max number of message events per span
LinkType values.
LinkType values.
LinkType values.
MessageEventType values.
MessageEventType values.
MessageEventType values.
All available span kinds. Span kind must be either one of these values.
All available span kinds. Span kind must be either one of these values.
All available span kinds. Span kind must be either one of these values.
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
samplePeriod is the minimum time between accepting spans in a single bucket.
The pages are generated with Goldsv0.3.2-preview. (GOOS=darwin GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.