package module
Version: v0.18.1 Latest Latest

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

Go to latest
Published: Nov 18, 2019 License: MIT Imports: 35 Imported by: 225



Circle CI MIT license GoDoc

The LightStep distributed tracing library for Go.

Looking for the LightStep OpenCensus exporter? Check out the lightstepoc package.


$ go get ''

API Documentation


Initialization: Starting a new tracer

To initialize a tracer, configure it with a valid Access Token and optional tuning parameters. Register the tracer as the OpenTracing global tracer so that it will become available to your installed instrumentation libraries.

import (

func main() {
  lightstepTracer := lightstep.NewTracer(lightstep.Options{
    AccessToken: "YourAccessToken",


Instrumenting Code: Using the OpenTracing API

All instrumentation should be done through the OpenTracing API, rather than using the lightstep tracer type directly. For API documentation and advice on instrumentation in general, see the opentracing godocs and the opentracing website.

Flushing and Closing: Managing the tracer lifecycle

As part of managing your application lifecycle, the lightstep tracer extends the opentracing.Tracer interface with methods for manual flushing and closing. To access these methods, you can take the global tracer and typecast it to a lightstep.Tracer. As a convenience, the lightstep package provides static methods which perform the typecasting.

import (

func shutdown(ctx context.Context) {
  // access the running tracer
  tracer := opentracing.GlobalTracer()
  // typecast from opentracing.Tracer to lightstep.Tracer
  lsTracer, ok := tracer.(lightstep.Tracer)
  if (!ok) { 

  // or use static methods
  lightstep.Close(ctx, tracer)

Event Handling: Observing the LightStep tracer

In order to connect diagnostic information from the lightstep tracer into an application's logging and metrics systems, inject an event handler using the OnEvent static method. Events may be typecast to check for errors or specific events such as status reports.

import (

logAndMetricsHandler := func(event lightstep.Event){
  switch event := event.(type) {
  case EventStatusReport:
    metrics.Count("tracer.dropped_spans", event.DroppedSpans())
  case ErrorEvent:
    logger.Error("LS Tracer error: %s", event)
    logger.Info("LS Tracer info: %s", event)

func main() {
  // setup event handler first to catch startup errors
  lightstepTracer := lightstep.NewTracer(lightstep.Options{
    AccessToken: "YourAccessToken",


Event handlers will receive events from any active tracers, as well as errors in static functions. It is suggested that you set up event handling before initializing your tracer to catch any errors on initialization.

Advanced Configuration: Transport and Serialization Protocols

By following the above configuration, the tracer will send information to LightStep using HTTP and Protocol Buffers which is the recommended configuration. If there are no specific transport protocol needs you have, there is no need to change this default.

There are two options for transport protocols:

  • Protocol Buffers over HTTP - The recommended and default solution.
  • Protocol Buffers over GRPC - This is a more advanced solution that might be desirable if you already have gRPC networking configured.

You can configure which transport protocol the tracer uses using the UseGRPC and UseHttp flags in the options.



Package lightstep implements the LightStep OpenTracing client for Go.



View Source
const (
	DefaultCollectorPath     = "/_rpc/v1/reports/binary"
	DefaultPlainPort         = 80
	DefaultSecurePort        = 443
	DefaultGRPCCollectorHost = ""

	DefaultMaxReportingPeriod = 2500 * time.Millisecond
	DefaultMinReportingPeriod = 500 * time.Millisecond
	DefaultMaxSpans           = 1000
	DefaultReportTimeout      = 30 * time.Second
	DefaultReconnectPeriod    = 5 * time.Minute

	DefaultMaxLogKeyLen   = 256
	DefaultMaxLogValueLen = 1024
	DefaultMaxLogsPerSpan = 500

	DefaultGRPCMaxCallSendMsgSizeBytes = math.MaxInt32

Default Option values.

View Source
const (
	ParentSpanGUIDKey = "parent_span_guid" // ParentSpanGUIDKey is the tag key used to record the relationship between child and parent spans.
	ComponentNameKey  = "lightstep.component_name"
	GUIDKey           = "lightstep.guid" // <- runtime guid, not span guid
	HostnameKey       = "lightstep.hostname"
	CommandLineKey    = "lightstep.command_line"

	TracerPlatformKey        = "lightstep.tracer_platform"
	TracerPlatformValue      = "go"
	TracerPlatformVersionKey = "lightstep.tracer_platform_version"
	TracerVersionKey         = "lightstep.tracer_version" // Note: TracerVersionValue is generated from ./VERSION

Tag and Tracer Attribute keys.

View Source
const BinaryCarrier = opentracing.Binary

BinaryCarrier is used as the format parameter in inject/extract for lighstep binary propagation.

View Source
const LSMetaEvent_ExtractOperation = "lightstep.extract_span"

operation names for ls meta span events

View Source
const LSMetaEvent_InjectOperation = "lightstep.inject_span"
View Source
const LSMetaEvent_MetaEventKey = "lightstep.meta_event"

keys for ls meta span events

View Source
const LSMetaEvent_PropagationFormatKey = "lightstep.propagation_format"
View Source
const LSMetaEvent_SpanFinishOperation = "lightstep.span_finish"
View Source
const LSMetaEvent_SpanIdKey = "lightstep.span_id"
View Source
const LSMetaEvent_SpanStartOperation = "lightstep.span_start"
View Source
const LSMetaEvent_TraceIdKey = "lightstep.trace_id"
View Source
const LSMetaEvent_TracerCreateOperation = "lightstep.tracer_create"
View Source
const LSMetaEvent_TracerGuidKey = "lightstep.tracer_guid"
View Source
const TracerVersionValue = "0.18.1"

TracerVersionValue provides the current version of the lightstep-tracer-go release


View Source
var B3Propagator b3Propagator

B3Propagator propagates context in the b3 format

View Source
var BinaryPropagator binaryPropagator

BinaryPropagator propagates context in binary format

View Source
var LightStepPropagator lightstepPropagator

LightStepPropagator propagates context in the LightStep format


func Close added in v0.15.0

func Close(ctx context.Context, tracer opentracing.Tracer)

Close synchronously flushes the tracer, then terminates it.

func CloseTracer added in v0.12.0

func CloseTracer(tracer opentracing.Tracer) error

CloseTracer closes the tracer DEPRECATED: use Close instead.

func Flush added in v0.15.0

func Flush(ctx context.Context, tracer opentracing.Tracer)

Flush forces a synchronous Flush.

func FlushLightStepTracer

func FlushLightStepTracer(tracer opentracing.Tracer) error

FlushLightStepTracer flushes the tracer DEPRECATED: use Flush instead.

func GetLightStepAccessToken

func GetLightStepAccessToken(tracer opentracing.Tracer) (string, error)

GetLightStepAccessToken returns the currently configured AccessToken.

func GetLightStepReporterID added in v0.15.2

func GetLightStepReporterID(tracer opentracing.Tracer) (uint64, error)

GetLightStepReporterID returns the currently configured Reporter ID.

func SetGlobalEventHandler added in v0.15.0

func SetGlobalEventHandler(handler EventHandler)

SetGlobalEventHandler sets a global handler to receive tracer events as they occur. Events may be emitted by the tracer, or by calls to static functions in this package. It is suggested that you set your EventHandler before starting your tracer, but it is safe to set a new handler at any time. Setting a new handler removes the previous one.

The EventHandler is called synchronously – do not block in your handler as it may interfere with the tracer. If no EventHandler handler is set, a LogOnceOnError handler is set by default.

NOTE: Event handling is for reporting purposes only. It is not intended as a mechanism for controling or restarting the tracer. Connection issues, retry logic, and other transient errors are handled internally by the tracer.


type Collector added in v0.17.0

type Collector interface {
	Report(context.Context, *collectorpb.ReportRequest) (*collectorpb.ReportResponse, error)

Collector encapsulates custom transport of protobuf messages

type Connection added in v0.13.0

type Connection interface {

Connection describes a closable connection. Exposed for testing.

type ConnectorFactory added in v0.13.0

type ConnectorFactory func() (interface{}, Connection, error)

ConnectorFactory is for testing purposes.

type Endpoint

type Endpoint struct {
	Scheme           string `yaml:"scheme" json:"scheme" usage:"scheme to use for the endpoint, defaults to appropriate one if no custom one is required"`
	Host             string `yaml:"host" json:"host" usage:"host on which the endpoint is running"`
	Port             int    `yaml:"port" json:"port" usage:"port on which the endpoint is listening"`
	Plaintext        bool   `yaml:"plaintext" json:"plaintext" usage:"whether or not to encrypt data send to the endpoint"`
	CustomCACertFile string `` /* 136-byte string literal not displayed */

Endpoint describes a collector or web API host/port and whether or not to use plaintext communication.

func (Endpoint) HostPort added in v0.13.0

func (e Endpoint) HostPort() string

HostPort use SocketAddress instead. DEPRECATED

func (Endpoint) SocketAddress added in v0.15.6

func (e Endpoint) SocketAddress() string

SocketAddress returns an address suitable for dialing grpc connections

func (Endpoint) URL added in v0.13.0

func (e Endpoint) URL() string

URL returns an address suitable for dialing thrift connections

type ErrorEvent added in v0.15.0

type ErrorEvent interface {
	Err() error

The ErrorEvent type can be used to filter events. The `Err` method returns the underlying error.

type Event added in v0.15.0

type Event interface {
	String() string

An Event is emitted by the LightStep tracer as a reporting mechanism. They are handled by registering an EventHandler callback via SetGlobalEventHandler. The emitted events may be cast to specific event types in order access additional information.

NOTE: To ensure that events can be accurately identified, each event type contains a sentinel method matching the name of the type. This method is a no-op, it is only used for type coersion.

type EventConnectionError added in v0.15.0

type EventConnectionError interface {

EventConnectionError occurs when the tracer fails to maintain it's connection with the Collector.

type EventFlushError added in v0.15.0

type EventFlushError interface {
	State() EventFlushErrorState

EventFlushError occurs when a flush fails to send. Call the `State` method to determine the type of error.

type EventFlushErrorState added in v0.15.0

type EventFlushErrorState string

EventFlushErrorState lists the possible causes for a flush to fail.

const (
	FlushErrorTracerClosed   EventFlushErrorState = "flush failed, the tracer is closed."
	FlushErrorTracerDisabled EventFlushErrorState = "flush failed, the tracer is disabled."
	FlushErrorTransport      EventFlushErrorState = "flush failed, could not send report to Collector"
	FlushErrorReport         EventFlushErrorState = "flush failed, report contained errors"
	FlushErrorTranslate      EventFlushErrorState = "flush failed, could not translate report"

Constant strings corresponding to flush errors

type EventHandler added in v0.15.0

type EventHandler func(Event)

An EventHandler can be registered with SetGlobalEventHandler to

func NewEventChannel added in v0.15.0

func NewEventChannel(buffer int) (EventHandler, <-chan Event)

NewEventChannel returns an SetGlobalEventHandler callback handler, and a channel that produces the errors. When the channel buffer is full, subsequent errors will be dropped. A buffer size of less than one is incorrect, and will be adjusted to a buffer size of one.

func NewEventLogOneError added in v0.15.0

func NewEventLogOneError() EventHandler

NewEventLogOneError logs the first error event that occurs.

func NewEventLogger added in v0.15.0

func NewEventLogger() EventHandler

NewEventLogger logs events using the standard go logger.

type EventStartError added in v0.15.0

type EventStartError interface {

EventStartError occurs if the Options passed to NewTracer are invalid, and the Tracer has failed to start.

type EventStatusReport added in v0.15.0

type EventStatusReport interface {
	StartTime() time.Time
	FinishTime() time.Time
	Duration() time.Duration
	SentSpans() int
	DroppedSpans() int
	EncodingErrors() int

EventStatusReport occurs on every successful flush. It contains all metrics collected since the previous successful flush.

type EventTracerDisabled added in v0.15.0

type EventTracerDisabled interface {

EventTracerDisabled occurs when a tracer is disabled by either the user or the collector.

type EventUnsupportedTracer added in v0.15.0

type EventUnsupportedTracer interface {
	Tracer() opentracing.Tracer

EventUnsupportedTracer occurs when a tracer being passed to a helper function fails to typecast as a LightStep tracer.

type EventUnsupportedValue added in v0.15.0

type EventUnsupportedValue interface {
	Key() string
	Value() interface{}

EventUnsupportedValue occurs when a tracer encounters an unserializable tag or log field.

type Options

type Options struct {
	// AccessToken is the unique API key for your LightStep project.  It is
	// available on your account page at
	AccessToken string `yaml:"access_token" usage:"access token for reporting to LightStep"`

	// Collector is the host, port, and plaintext option to use
	// for the collector.
	Collector Endpoint `yaml:"collector"`

	// Tags are arbitrary key-value pairs that apply to all spans generated by
	// this Tracer.
	Tags opentracing.Tags

	// LightStep is the host, port, and plaintext option to use
	// for the LightStep web API.
	LightStepAPI Endpoint `yaml:"lightstep_api"`

	// MaxBufferedSpans is the maximum number of spans that will be buffered
	// before sending them to a collector.
	MaxBufferedSpans int `yaml:"max_buffered_spans"`

	// MaxLogKeyLen is the maximum allowable size (in characters) of an
	// OpenTracing logging key. Longer keys are truncated.
	MaxLogKeyLen int `yaml:"max_log_key_len"`

	// MaxLogValueLen is the maximum allowable size (in characters) of an
	// OpenTracing logging value. Longer values are truncated. Only applies to
	// variable-length value types (strings, interface{}, etc).
	MaxLogValueLen int `yaml:"max_log_value_len"`

	// MaxLogsPerSpan limits the number of logs in a single span.
	MaxLogsPerSpan int `yaml:"max_logs_per_span"`

	// GRPCMaxCallSendMsgSizeBytes limits the size in bytes of grpc messages
	// sent by a client.
	GRPCMaxCallSendMsgSizeBytes int `yaml:"grpc_max_call_send_msg_size_bytes"`

	// ReportingPeriod is the maximum duration of time between sending spans
	// to a collector.  If zero, the default will be used.
	ReportingPeriod time.Duration `yaml:"reporting_period"`

	// MinReportingPeriod is the minimum duration of time between sending spans
	// to a collector.  If zero, the default will be used. It is strongly
	// recommended to use the default.
	MinReportingPeriod time.Duration `yaml:"min_reporting_period"`

	ReportTimeout time.Duration `yaml:"report_timeout"`

	// DropSpanLogs turns log events on all Spans into no-ops.
	DropSpanLogs bool `yaml:"drop_span_logs"`

	// DEPRECATED: The LightStep library prints the first error to stdout by default.
	// See the documentation on the SetGlobalEventHandler function for guidance on
	// how to integrate tracer diagnostics with your application's logging and
	// metrics systems.
	Verbose bool `yaml:"verbose"`

	// Force the use of a specific transport protocol. If multiple are set to true,
	// the following order is used to select for the first option: http, grpc.
	// If none are set to true, HTTP is defaulted to.
	UseHttp bool `yaml:"use_http"`
	UseGRPC bool `yaml:"usegrpc"`

	// Propagators allow inject/extract to use custom propagators for different formats. This
	// package includes a `B3Propagator` that supports B3 headers on text maps and http headers.
	// Defaults:
	//   opentracing.HTTPHeaders: LightStepPropagator
	//   opentracing.TextMap: LightStepPropagator,
	//   opentracing.Binary: LightStepPropagator
	Propagators map[opentracing.BuiltinFormat]Propagator `yaml:"-"`

	// CustomCollector allows customizing the Protobuf transport.
	// This is an advanced feature that avoids reconnect logic.
	CustomCollector Collector `yaml:"-" json:"-"`

	ReconnectPeriod time.Duration `yaml:"reconnect_period"`

	// DialOptions allows customizing the grpc dial options passed to the grpc.Dial(...) call.
	// This is an advanced feature added to allow for a custom balancer or middleware.
	// It can be safely ignored if you have no custom dialing requirements.
	// If UseGRPC is not set, these dial options are ignored.
	DialOptions []grpc.DialOption `yaml:"-" json:"-"`

	// A hook for receiving finished span events
	Recorder SpanRecorder `yaml:"-" json:"-"`

	// For testing purposes only
	ConnFactory ConnectorFactory `yaml:"-" json:"-"`

	// Enable LightStep Meta Event Logging
	MetaEventReportingEnabled bool `yaml:"meta_event_reporting_enabled" json:"meta_event_reporting_enabled"`

Options control how the LightStep Tracer behaves.

func (*Options) Initialize added in v0.13.0

func (opts *Options) Initialize() error

Initialize validates options, and sets default values for unset options. This is called automatically when creating a new Tracer.

func (*Options) Validate added in v0.15.0

func (opts *Options) Validate() error

Validate checks that all required fields are set, and no options are incorrectly configured.

type Propagator added in v0.18.0

type Propagator interface {
	Inject(opentracing.SpanContext, interface{}) error
	Extract(interface{}) (opentracing.SpanContext, error)

Propagator provides the ability to inject/extract different formats of span information. Currently supported: ls, b3

type PropagatorStack added in v0.18.1

type PropagatorStack struct {
	// contains filtered or unexported fields

PropagatorStack provides a Propagator interface that supports multiple propagators per format.

func (PropagatorStack) Extract added in v0.18.1

func (stack PropagatorStack) Extract(
	opaqueCarrier interface{},
) (opentracing.SpanContext, error)

Extract iterates through configured propagators and returns the first successfully extracted context

func (PropagatorStack) Inject added in v0.18.1

func (stack PropagatorStack) Inject(
	spanContext opentracing.SpanContext,
	opaqueCarrier interface{},
) error

Inject iterates through configured propagators and calls their Inject functions

func (*PropagatorStack) PushPropagator added in v0.18.1

func (stack *PropagatorStack) PushPropagator(p Propagator)

PushPropagator adds a Propagator to a list of configured propagators

type RawSpan added in v0.13.0

type RawSpan struct {
	// Those recording the RawSpan should also record the contents of its
	// SpanContext.
	Context SpanContext

	// The SpanID of this SpanContext's first intra-trace reference (i.e.,
	// "parent"), or 0 if there is no parent.
	ParentSpanID uint64

	// The name of the "operation" this span is an instance of. (Called a "span
	// name" in some implementations)
	Operation string

	// We store <start, duration> rather than <start, end> so that only
	// one of the timestamps has global clock uncertainty issues.
	Start    time.Time
	Duration time.Duration

	// Essentially an extension mechanism. Can be used for many purposes,
	// not to be enumerated here.
	Tags opentracing.Tags

	// The span's "microlog".
	Logs []opentracing.LogRecord

RawSpan encapsulates all state associated with a (finished) LightStep Span.

type SetParentSpanID

type SetParentSpanID uint64

SetParentSpanID is an opentracing.StartSpanOption that sets an explicit parent SpanID. It must be used in conjunction with SetTraceID or the result is undefined. If the value is zero, it will be disregarded. If a ChildOf or FollowsFrom span relation is also set in the start options, it will override this value.

func (SetParentSpanID) Apply

func (sid SetParentSpanID) Apply(sso *opentracing.StartSpanOptions)

Apply satisfies the StartSpanOption interface.

type SetSpanID

type SetSpanID uint64

SetSpanID is a opentracing.StartSpanOption that sets an explicit SpanID. It must be used in conjunction with SetTraceID or the result is undefined.

func (SetSpanID) Apply

func (sid SetSpanID) Apply(sso *opentracing.StartSpanOptions)

Apply satisfies the StartSpanOption interface.

type SetTraceID

type SetTraceID uint64

SetTraceID is an opentracing.StartSpanOption that sets an explicit TraceID. It must be used in order to set an explicit SpanID or ParentSpanID. If a ChildOf or FollowsFrom span relation is also set in the start options, it will override this value.

func (SetTraceID) Apply

func (sid SetTraceID) Apply(sso *opentracing.StartSpanOptions)

Apply satisfies the StartSpanOption interface.

type SpanContext added in v0.13.0

type SpanContext struct {
	// A probabilistically unique identifier for a [multi-span] trace.
	TraceID uint64

	// Most significant bits of a 128-bit TraceID
	TraceIDUpper uint64

	// A probabilistically unique identifier for a span.
	SpanID uint64

	// Propagates sampling decision
	Sampled string

	// The span's associated baggage.
	Baggage map[string]string // initialized on first use

SpanContext holds lightstep-specific Span metadata.

func (SpanContext) ForeachBaggageItem added in v0.13.0

func (c SpanContext) ForeachBaggageItem(handler func(k, v string) bool)

ForeachBaggageItem belongs to the opentracing.SpanContext interface

func (SpanContext) WithBaggageItem added in v0.13.0

func (c SpanContext) WithBaggageItem(key, val string) SpanContext

WithBaggageItem returns an entirely new basictracer SpanContext with the given key:value baggage pair set.

type SpanRecorder added in v0.13.0

type SpanRecorder interface {

A SpanRecorder handles all of the `RawSpan` data generated via an associated `Tracer` instance.

type Tracer added in v0.13.0

type Tracer interface {

	// Close flushes and then terminates the LightStep collector
	// Flush sends all spans currently in the buffer to the LighStep collector
	// Options gets the Options used in New() or NewWithOptions().
	Options() Options
	// Disable prevents the tracer from recording spans or flushing

Tracer extends the `opentracing.Tracer` interface with methods for manual flushing and closing. To access these methods, you can take the global tracer and typecast it to a `lightstep.Tracer`. As a convenience, the lightstep package provides static functions which perform the typecasting.

func CreateTracer added in v0.18.0

func CreateTracer(opts Options) (Tracer, error)

CreateTracer creates and starts a new Lightstep Tracer. It is meant to replace NewTracer which does not propagate the error.

func NewTracer

func NewTracer(opts Options) Tracer

NewTracer creates and starts a new Lightstep Tracer. In case of error, we emit event and return nil.

type Tracerv0_14 added in v0.15.0

type Tracerv0_14 interface {

	// DEPRECATED: error is always nil. Equivalent to Tracer.Close(context.Background())
	Close() error
	// DEPRECATED: error is always nil. Equivalent to Tracer.Flush(context.Background())
	Flush() error
	// Options gets the Options used in New().
	Options() Options
	// Disable prevents the tracer from recording spans or flushing.

Tracerv0_14 matches the Tracer interface from v0.14.0 DEPRECATED

func NewTracerv0_14 added in v0.15.0

func NewTracerv0_14(opts Options) Tracerv0_14

NewTracerv0_14 returns a tracer which conforms to the Tracer interface from v0.14.0, for backwards compatibility. DEPRECATED


Path Synopsis
Based on the quickstart tutorial available at
Based on the quickstart tutorial available at
Code generated by counterfeiter.
Code generated by counterfeiter.
Package lightstepoc provides an OpenCensus exporter for sending OpenCensus spans back to LightStep.
Package lightstepoc provides an OpenCensus exporter for sending OpenCensus spans back to LightStep.

Jump to

Keyboard shortcuts

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