trace

package
v0.0.0-...-52b58a3 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2022 License: Apache-2.0, Apache-2.0, Apache-2.0 Imports: 9 Imported by: 0

Documentation

Overview

Package trace provides an implementation of the tracing part of the OpenTelemetry API.

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.

To participate in distributed traces a Span needs to be created for the operation being performed as part of a traced workflow. It its simplest form:

var tracer trace.Tracer

func init() {
	tracer = otel.Tracer("instrumentation/package/name")
}

func operation(ctx context.Context) {
	var span trace.Span
	ctx, span = tracer.Start(ctx, "operation")
	defer span.End()
	// ...
}

A Tracer is unique to the instrumentation and is used to create Spans. Instrumentation should be designed to accept a TracerProvider from which it can create its own unique Tracer. Alternatively, the registered global TracerProvider from the go.opentelemetry.io/otel package can be used as a default.

const (
	name    = "instrumentation/package/name"
	version = "0.1.0"
)

type Instrumentation struct {
	tracer trace.Tracer
}

func NewInstrumentation(tp trace.TracerProvider) *Instrumentation {
	if tp == nil {
		tp = otel.TracerProvider()
	}
	return &Instrumentation{
		tracer: tp.Tracer(name, trace.WithInstrumentationVersion(version)),
	}
}

func operation(ctx context.Context, inst *Instrumentation) {
	var span trace.Span
	ctx, span = inst.tracer.Start(ctx, "operation")
	defer span.End()
	// ...
}

Index

Constants

View Source
const (
	// FlagsSampled is a bitmask with the sampled bit set. A SpanContext
	// with the sampling bit set means the span is sampled.
	FlagsSampled = TraceFlags(0x01)
)

Variables

This section is empty.

Functions

func ContextWithRemoteSpanContext

func ContextWithRemoteSpanContext(parent context.Context, rsc SpanContext) context.Context

ContextWithRemoteSpanContext returns a copy of parent with rsc set explicly as a remote SpanContext and as the current Span. The Span implementation that wraps rsc is non-recording and performs no operations other than to return rsc as the SpanContext from the SpanContext method.

func ContextWithSpan

func ContextWithSpan(parent context.Context, span Span) context.Context

ContextWithSpan returns a copy of parent with span set as the current Span.

func ContextWithSpanContext

func ContextWithSpanContext(parent context.Context, sc SpanContext) context.Context

ContextWithSpanContext returns a copy of parent with sc as the current Span. The Span implementation that wraps sc is non-recording and performs no operations other than to return sc as the SpanContext from the SpanContext method.

Types

type Event

type Event struct {
	// Name is the name of this event
	Name string

	// Attributes describe the aspects of the event.
	Attributes []attribute.KeyValue

	// DroppedAttributeCount is the number of attributes that were not
	// recorded due to configured limits being reached.
	DroppedAttributeCount int

	// Time at which this event was recorded.
	Time time.Time
}

Event is a thing that happened during a Span's lifetime.

type EventOption

type EventOption interface {
	ApplyEvent(*SpanConfig)
	// contains filtered or unexported methods
}

EventOption applies span event options to a SpanConfig.

type InstrumentationOption

type InstrumentationOption interface {
	TracerOption
}

InstrumentationOption is an interface for applying instrumentation specific options.

func WithInstrumentationVersion

func WithInstrumentationVersion(version string) InstrumentationOption

WithInstrumentationVersion sets the instrumentation version.

type LifeCycleOption

type LifeCycleOption interface {
	SpanOption
	EventOption
}

LifeCycleOption applies span life-cycle options to a SpanConfig. These options set values releated to events in a spans life-cycle like starting, ending, experiencing an error and other user defined notable events.

func WithAttributes

func WithAttributes(attributes ...attribute.KeyValue) LifeCycleOption

WithAttributes adds the attributes related to a span life-cycle event. These attributes are used to describe the work a Span represents when this option is provided to a Span's start or end events. Otherwise, these attributes provide additional information about the event being recorded (e.g. error, state change, processing progress, system event).

If multiple of these options are passed the attributes of each successive option will extend the attributes instead of overwriting. There is no guarantee of uniqueness in the resulting attributes.

func WithTimestamp

func WithTimestamp(t time.Time) LifeCycleOption

WithTimestamp sets the time of a Span life-cycle moment (e.g. started, stopped, errored).

type Link struct {
	// SpanContext of the linked Span.
	SpanContext

	// Attributes describe the aspects of the link.
	Attributes []attribute.KeyValue

	// DroppedAttributeCount is the number of attributes that were not
	// recorded due to configured limits being reached.
	DroppedAttributeCount int
}

Link is the relationship between two Spans. The relationship can be within the same Trace or across different Traces.

For example, a Link is used in the following situations:

  1. Batch Processing: A batch of operations may contain operations associated with one or more traces/spans. Since there can only be one parent SpanContext, a Link is used to keep reference to the SpanContext of all operations in the batch.
  2. Public Endpoint: A SpanContext for an in incoming client request on a public endpoint should be considered untrusted. In such a case, a new trace with its own identity and sampling decision needs to be created, but this new trace needs to be related to the original trace in some form. A Link is used to keep reference to the original SpanContext and track the relationship.

type Span

type Span interface {
	// Tracer returns the Tracer that created the Span. Tracer MUST NOT be
	// nil.
	Tracer() Tracer

	// End completes the Span. The Span is considered complete and ready to be
	// delivered through the rest of the telemetry pipeline after this method
	// is called. Therefore, updates to the Span are not allowed after this
	// method has been called.
	End(options ...SpanOption)

	// AddEvent adds an event with the provided name and options.
	AddEvent(name string, options ...EventOption)

	// IsRecording returns the recording state of the Span. It will return
	// true if the Span is active and events can be recorded.
	IsRecording() bool

	// RecordError will record err as an exception span event for this span. An
	// additional call toSetStatus is required if the Status of the Span should
	// be set to Error, this method does not change the Span status. If this
	// span is not being recorded or err is nil than this method does nothing.
	RecordError(err error, options ...EventOption)

	// SpanContext returns the SpanContext of the Span. The returned
	// SpanContext is usable even after the End has been called for the Span.
	SpanContext() SpanContext

	// SetStatus sets the status of the Span in the form of a code and a
	// message. SetStatus overrides the value of previous calls to SetStatus
	// on the Span.
	SetStatus(code codes.Code, msg string)

	// SetName sets the Span name.
	SetName(name string)

	// SetAttributes sets kv as attributes of the Span. If a key from kv
	// already exists for an attribute of the Span it will be overwritten with
	// the value contained in kv.
	SetAttributes(kv ...attribute.KeyValue)
}

Span is the individual component of a trace. It represents a single named and timed operation of a workflow that is traced. A Tracer is used to create a Span and it is then up to the operation the Span represents to properly end the Span when the operation itself ends.

func SpanFromContext

func SpanFromContext(ctx context.Context) Span

SpanFromContext returns the current Span from ctx.

If no Span is currently set in ctx an implementation of a Span that performs no operations is returned.

type SpanConfig

type SpanConfig struct {
	// Attributes describe the associated qualities of a Span.
	Attributes []attribute.KeyValue
	// Timestamp is a time in a Span life-cycle.
	Timestamp time.Time
	// Links are the associations a Span has with other Spans.
	Links []Link
	// NewRoot identifies a Span as the root Span for a new trace. This is
	// commonly used when an existing trace crosses trust boundaries and the
	// remote parent span context should be ignored for security.
	NewRoot bool
	// SpanKind is the role a Span has in a trace.
	SpanKind SpanKind
}

SpanConfig is a group of options for a Span.

func NewEventConfig

func NewEventConfig(options ...EventOption) *SpanConfig

NewEventConfig applies all the EventOptions to a returned SpanConfig. If no timestamp option is passed, the returned SpanConfig will have a Timestamp set to the call time, otherwise no validation is performed on the returned SpanConfig.

func NewSpanConfig

func NewSpanConfig(options ...SpanOption) *SpanConfig

NewSpanConfig applies all the options to a returned SpanConfig. No validation is performed on the returned SpanConfig (e.g. no uniqueness checking or bounding of data), it is left to the SDK to perform this action.

type SpanContext

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

SpanContext contains identifying trace information about a Span.

func NewSpanContext

func NewSpanContext(config SpanContextConfig) SpanContext

NewSpanContext constructs a SpanContext using values from the provided SpanContextConfig.

func SpanContextFromContext

func SpanContextFromContext(ctx context.Context) SpanContext

SpanContextFromContext returns the current Span's SpanContext.

func (SpanContext) Equal

func (sc SpanContext) Equal(other SpanContext) bool

Equal is a predicate that determines whether two SpanContext values are equal.

func (SpanContext) HasSpanID

func (sc SpanContext) HasSpanID() bool

HasSpanID checks if the SpanContext has a valid SpanID.

func (SpanContext) HasTraceID

func (sc SpanContext) HasTraceID() bool

HasTraceID checks if the SpanContext has a valid TraceID.

func (SpanContext) IsRemote

func (sc SpanContext) IsRemote() bool

IsRemote indicates whether the SpanContext represents a remotely-created Span.

func (SpanContext) IsSampled

func (sc SpanContext) IsSampled() bool

IsSampled returns if the sampling bit is set in the SpanContext's TraceFlags.

func (SpanContext) IsValid

func (sc SpanContext) IsValid() bool

IsValid returns if the SpanContext is valid. A valid span context has a valid TraceID and SpanID.

func (SpanContext) MarshalJSON

func (sc SpanContext) MarshalJSON() ([]byte, error)

MarshalJSON implements a custom marshal function to encode a SpanContext.

func (SpanContext) SpanID

func (sc SpanContext) SpanID() SpanID

SpanID returns the SpanID from the SpanContext.

func (SpanContext) TraceFlags

func (sc SpanContext) TraceFlags() TraceFlags

TraceFlags returns the flags from the SpanContext.

func (SpanContext) TraceID

func (sc SpanContext) TraceID() TraceID

TraceID returns the TraceID from the SpanContext.

func (SpanContext) TraceState

func (sc SpanContext) TraceState() TraceState

TraceState returns the TraceState from the SpanContext.

func (SpanContext) WithRemote

func (sc SpanContext) WithRemote(remote bool) SpanContext

WithRemote returns a copy of sc with the Remote property set to remote.

func (SpanContext) WithSpanID

func (sc SpanContext) WithSpanID(spanID SpanID) SpanContext

WithSpanID returns a new SpanContext with the SpanID replaced.

func (SpanContext) WithTraceFlags

func (sc SpanContext) WithTraceFlags(flags TraceFlags) SpanContext

WithTraceFlags returns a new SpanContext with the TraceFlags replaced.

func (SpanContext) WithTraceID

func (sc SpanContext) WithTraceID(traceID TraceID) SpanContext

WithTraceID returns a new SpanContext with the TraceID replaced.

func (SpanContext) WithTraceState

func (sc SpanContext) WithTraceState(state TraceState) SpanContext

WithTraceState returns a new SpanContext with the TraceState replaced.

type SpanContextConfig

type SpanContextConfig struct {
	TraceID    TraceID
	SpanID     SpanID
	TraceFlags TraceFlags
	TraceState TraceState
	Remote     bool
}

SpanContextConfig contains mutable fields usable for constructing an immutable SpanContext.

type SpanID

type SpanID [8]byte

SpanID is a unique identity of a span in a trace.

func SpanIDFromHex

func SpanIDFromHex(h string) (SpanID, error)

SpanIDFromHex returns a SpanID from a hex string if it is compliant with the w3c trace-context specification. See more at https://www.w3.org/TR/trace-context/#parent-id

func (SpanID) IsValid

func (s SpanID) IsValid() bool

IsValid checks whether the SpanID is valid. A valid SpanID does not consist of zeros only.

func (SpanID) MarshalJSON

func (s SpanID) MarshalJSON() ([]byte, error)

MarshalJSON implements a custom marshal function to encode SpanID as a hex string.

func (SpanID) String

func (s SpanID) String() string

String returns the hex string representation form of a SpanID

type SpanKind

type SpanKind int

SpanKind is the role a Span plays in a Trace.

const (
	// SpanKindUnspecified is an unspecified SpanKind and is not a valid
	// SpanKind. SpanKindUnspecified should be replaced with SpanKindInternal
	// if it is received.
	SpanKindUnspecified SpanKind = 0
	// SpanKindInternal is a SpanKind for a Span that represents an internal
	// operation within an application.
	SpanKindInternal SpanKind = 1
	// SpanKindServer is a SpanKind for a Span that represents the operation
	// of handling a request from a client.
	SpanKindServer SpanKind = 2
	// SpanKindClient is a SpanKind for a Span that represents the operation
	// of client making a request to a server.
	SpanKindClient SpanKind = 3
	// SpanKindProducer is a SpanKind for a Span that represents the operation
	// of a producer sending a message to a message broker. Unlike
	// SpanKindClient and SpanKindServer, there is often no direct
	// relationship between this kind of Span and a SpanKindConsumer kind. A
	// SpanKindProducer Span will end once the message is accepted by the
	// message broker which might not overlap with the processing of that
	// message.
	SpanKindProducer SpanKind = 4
	// SpanKindConsumer is a SpanKind for a Span that represents the operation
	// of a consumer receiving a message from a message broker. Like
	// SpanKindProducer Spans, there is often no direct relationship between
	// this Span and the Span that produced the message.
	SpanKindConsumer SpanKind = 5
)

As a convenience, these match the proto definition, see https://github.com/open-telemetry/opentelemetry-proto/blob/30d237e1ff3ab7aa50e0922b5bebdd93505090af/opentelemetry/proto/trace/v1/trace.proto#L101-L129

The unspecified value is not a valid `SpanKind`. Use `ValidateSpanKind()` to coerce a span kind to a valid value.

func ValidateSpanKind

func ValidateSpanKind(spanKind SpanKind) SpanKind

ValidateSpanKind returns a valid span kind value. This will coerce invalid values into the default value, SpanKindInternal.

func (SpanKind) String

func (sk SpanKind) String() string

String returns the specified name of the SpanKind in lower-case.

type SpanOption

type SpanOption interface {
	ApplySpan(*SpanConfig)
	// contains filtered or unexported methods
}

SpanOption applies an option to a SpanConfig.

func WithLinks(links ...Link) SpanOption

WithLinks adds links to a Span. The links are added to the existing Span links, i.e. this does not overwrite.

func WithNewRoot

func WithNewRoot() SpanOption

WithNewRoot specifies that the Span should be treated as a root Span. Any existing parent span context will be ignored when defining the Span's trace identifiers.

func WithSpanKind

func WithSpanKind(kind SpanKind) SpanOption

WithSpanKind sets the SpanKind of a Span.

type TraceFlags

type TraceFlags byte //nolint:golint

TraceFlags contains flags that can be set on a SpanContext

func (TraceFlags) IsSampled

func (tf TraceFlags) IsSampled() bool

IsSampled returns if the sampling bit is set in the TraceFlags.

func (TraceFlags) MarshalJSON

func (tf TraceFlags) MarshalJSON() ([]byte, error)

MarshalJSON implements a custom marshal function to encode TraceFlags as a hex string.

func (TraceFlags) String

func (tf TraceFlags) String() string

String returns the hex string representation form of TraceFlags

func (TraceFlags) WithSampled

func (tf TraceFlags) WithSampled(sampled bool) TraceFlags

WithSampled sets the sampling bit in a new copy of the TraceFlags.

type TraceID

type TraceID [16]byte

TraceID is a unique identity of a trace. nolint:golint

func TraceIDFromHex

func TraceIDFromHex(h string) (TraceID, error)

TraceIDFromHex returns a TraceID from a hex string if it is compliant with the W3C trace-context specification. See more at https://www.w3.org/TR/trace-context/#trace-id nolint:golint

func (TraceID) IsValid

func (t TraceID) IsValid() bool

IsValid checks whether the trace TraceID is valid. A valid trace ID does not consist of zeros only.

func (TraceID) MarshalJSON

func (t TraceID) MarshalJSON() ([]byte, error)

MarshalJSON implements a custom marshal function to encode TraceID as a hex string.

func (TraceID) String

func (t TraceID) String() string

String returns the hex string representation form of a TraceID

type TraceState

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

TraceState provides additional vendor-specific trace identification information across different distributed tracing systems. It represents an immutable list consisting of key/value pairs. There can be a maximum of 32 entries in the list.

Key and value of each list member must be valid according to the W3C Trace Context specification (see https://www.w3.org/TR/trace-context-1/#key and https://www.w3.org/TR/trace-context-1/#value respectively).

Trace state must be valid according to the W3C Trace Context specification at all times. All mutating operations validate their input and, in case of valid parameters, return a new TraceState.

func TraceStateFromKeyValues

func TraceStateFromKeyValues(kvs ...attribute.KeyValue) (TraceState, error)

TraceStateFromKeyValues is a convenience method to create a new TraceState from provided key/value pairs.

func (TraceState) Delete

func (ts TraceState) Delete(key attribute.Key) (TraceState, error)

Delete removes specified entry from the trace state.

func (TraceState) Get

func (ts TraceState) Get(key attribute.Key) attribute.Value

Get returns a value for given key from the trace state. If no key is found or provided key is invalid, returns an empty value.

func (TraceState) Insert

func (ts TraceState) Insert(entry attribute.KeyValue) (TraceState, error)

Insert adds a new key/value, if one doesn't exists; otherwise updates the existing entry. The new or updated entry is always inserted at the beginning of the TraceState, i.e. on the left side, as per the W3C Trace Context specification requirement.

func (TraceState) IsEmpty

func (ts TraceState) IsEmpty() bool

IsEmpty returns true if the TraceState does not contain any entries

func (TraceState) MarshalJSON

func (ts TraceState) MarshalJSON() ([]byte, error)

MarshalJSON implements a custom marshal function to encode trace state.

func (TraceState) String

func (ts TraceState) String() string

String returns trace state as a string valid according to the W3C Trace Context specification.

type Tracer

type Tracer interface {
	// Start creates a span.
	Start(ctx context.Context, spanName string, opts ...SpanOption) (context.Context, Span)
}

Tracer is the creator of Spans.

type TracerConfig

type TracerConfig struct {
	// InstrumentationVersion is the version of the library providing
	// instrumentation.
	InstrumentationVersion string
}

TracerConfig is a group of options for a Tracer.

func NewTracerConfig

func NewTracerConfig(options ...TracerOption) *TracerConfig

NewTracerConfig applies all the options to a returned TracerConfig.

type TracerOption

type TracerOption interface {
	ApplyTracer(*TracerConfig)
	// contains filtered or unexported methods
}

TracerOption applies an option to a TracerConfig.

type TracerProvider

type TracerProvider interface {
	// Tracer creates an implementation of the Tracer interface.
	// The instrumentationName must be the name of the library providing
	// instrumentation. This name may be the same as the instrumented code
	// only if that code provides built-in instrumentation. If the
	// instrumentationName is empty, then a implementation defined default
	// name will be used instead.
	//
	// This method must be concurrency safe.
	Tracer(instrumentationName string, opts ...TracerOption) Tracer
}

TracerProvider provides access to instrumentation Tracers.

func NewNoopTracerProvider

func NewNoopTracerProvider() TracerProvider

NewNoopTracerProvider returns an implementation of TracerProvider that performs no operations. The Tracer and Spans created from the returned TracerProvider also perform no operations.

Jump to

Keyboard shortcuts

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