Categorygithub.com/agilebits/jaeger-client-go
modulepackage
2.25.0+incompatible
Repository: https://github.com/agilebits/jaeger-client-go.git
Documentation: pkg.go.dev

# README

GoDoc Build Status Coverage Status OpenTracing 1.0 Enabled

Jaeger Bindings for Go OpenTracing API

Instrumentation library that implements an OpenTracing Go Tracer for Jaeger (https://jaegertracing.io).

IMPORTANT: The library's import path is based on its original location under github.com/uber. Do not try to import it as github.com/jaegertracing, it will not compile. We might revisit this in the next major release.

  • :white_check_mark: import "github.com/uber/jaeger-client-go"
  • :x: import "github.com/jaegertracing/jaeger-client-go"

How to Contribute

Please see CONTRIBUTING.md.

Installation

We recommended using a dependency manager like dep and semantic versioning when including this library into an application. For example, Jaeger backend imports this library like this:

[[constraint]]
  name = "github.com/uber/jaeger-client-go"
  version = "2.17"

If you instead want to use the latest version in master, you can pull it via go get. Note that during go get you may see build errors due to incompatible dependencies, which is why we recommend using semantic versions for dependencies. The error may be fixed by running make install (it will install dep if you don't have it):

go get -u github.com/uber/jaeger-client-go/
cd $GOPATH/src/github.com/uber/jaeger-client-go/
git submodule update --init --recursive
make install

Initialization

See tracer initialization examples in godoc and config/example_test.go.

Environment variables

The tracer can be initialized with values coming from environment variables, if it is built from a config that was created via FromEnv(). None of the env vars are required and all of them can be overridden via direct setting of the property on the configuration object.

PropertyDescription
JAEGER_SERVICE_NAMEThe service name.
JAEGER_AGENT_HOSTThe hostname for communicating with agent via UDP (default localhost).
JAEGER_AGENT_PORTThe port for communicating with agent via UDP (default 6831).
JAEGER_ENDPOINTThe HTTP endpoint for sending spans directly to a collector, i.e. http://jaeger-collector:14268/api/traces. If specified, the agent host/port are ignored.
JAEGER_USERUsername to send as part of "Basic" authentication to the collector endpoint.
JAEGER_PASSWORDPassword to send as part of "Basic" authentication to the collector endpoint.
JAEGER_REPORTER_LOG_SPANSWhether the reporter should also log the spans" true or false (default false).
JAEGER_REPORTER_MAX_QUEUE_SIZEThe reporter's maximum queue size (default 100).
JAEGER_REPORTER_FLUSH_INTERVALThe reporter's flush interval, with units, e.g. 500ms or 2s (valid units; default 1s).
JAEGER_REPORTER_ATTEMPT_RECONNECTING_DISABLEDWhen true, disables udp connection helper that periodically re-resolves the agent's hostname and reconnects if there was a change (default false).
JAEGER_REPORTER_ATTEMPT_RECONNECT_INTERVALControls how often the agent client re-resolves the provided hostname in order to detect address changes (valid units; default 30s).
JAEGER_SAMPLER_TYPEThe sampler type: remote, const, probabilistic, ratelimiting (default remote). See also https://www.jaegertracing.io/docs/latest/sampling/.
JAEGER_SAMPLER_PARAMThe sampler parameter (number).
JAEGER_SAMPLER_MANAGER_HOST_PORT(deprecated) The HTTP endpoint when using the remote sampler.
JAEGER_SAMPLING_ENDPOINTThe URL for the sampling configuration server when using sampler type remote (default http://127.0.0.1:5778/sampling).
JAEGER_SAMPLER_MAX_OPERATIONSThe maximum number of operations that the sampler will keep track of (default 2000).
JAEGER_SAMPLER_REFRESH_INTERVALHow often the remote sampler should poll the configuration server for the appropriate sampling strategy, e.g. "1m" or "30s" (valid units; default 1m).
JAEGER_TAGSA comma separated list of name=value tracer-level tags, which get added to all reported spans. The value can also refer to an environment variable using the format ${envVarName:defaultValue}.
JAEGER_DISABLEDWhether the tracer is disabled or not. If true, the opentracing.NoopTracer is used (default false).
JAEGER_RPC_METRICSWhether to store RPC metrics, true or false (default false).

By default, the client sends traces via UDP to the agent at localhost:6831. Use JAEGER_AGENT_HOST and JAEGER_AGENT_PORT to send UDP traces to a different host:port. If JAEGER_ENDPOINT is set, the client sends traces to the endpoint via HTTP, making the JAEGER_AGENT_HOST and JAEGER_AGENT_PORT unused. If JAEGER_ENDPOINT is secured, HTTP basic authentication can be performed by setting the JAEGER_USER and JAEGER_PASSWORD environment variables.

Closing the tracer via io.Closer

The constructor function for Jaeger Tracer returns the tracer itself and an io.Closer instance. It is recommended to structure your main() so that it calls the Close() function on the closer before exiting, e.g.

tracer, closer, err := cfg.NewTracer(...)
defer closer.Close()

This is especially useful for command-line tools that enable tracing, as well as for the long-running apps that support graceful shutdown. For example, if your deployment system sends SIGTERM instead of killing the process and you trap that signal to do a graceful exit, then having defer closer.Close() ensures that all buffered spans are flushed.

Metrics & Monitoring

The tracer emits a number of different metrics, defined in metrics.go. The monitoring backend is expected to support tag-based metric names, e.g. instead of statsd-style string names like counters.my-service.jaeger.spans.started.sampled, the metrics are defined by a short name and a collection of key/value tags, for example: name:jaeger.traces, state:started, sampled:y. See metrics.go file for the full list and descriptions of emitted metrics.

The monitoring backend is represented by the metrics.Factory interface from package "github.com/uber/jaeger-lib/metrics". An implementation of that interface can be passed as an option to either the Configuration object or the Tracer constructor, for example:

import (
    "github.com/uber/jaeger-client-go/config"
    "github.com/uber/jaeger-lib/metrics/prometheus"
)

    metricsFactory := prometheus.New()
    tracer, closer, err := config.Configuration{
        ServiceName: "your-service-name",
    }.NewTracer(
        config.Metrics(metricsFactory),
    )

By default, a no-op metrics.NullFactory is used.

Logging

The tracer can be configured with an optional logger, which will be used to log communication errors, or log spans if a logging reporter option is specified in the configuration. The logging API is abstracted by the Logger interface. A logger instance implementing this interface can be set on the Config object before calling the New method.

Besides the zap implementation bundled with this package there is also a go-kit one in the jaeger-lib repository.

Instrumentation for Tracing

Since this tracer is fully compliant with OpenTracing API 1.0, all code instrumentation should only use the API itself, as described in the opentracing-go documentation.

Features

Reporters

A "reporter" is a component that receives the finished spans and reports them to somewhere. Under normal circumstances, the Tracer should use the default RemoteReporter, which sends the spans out of process via configurable "transport". For testing purposes, one can use an InMemoryReporter that accumulates spans in a buffer and allows to retrieve them for later verification. Also available are NullReporter, a no-op reporter that does nothing, a LoggingReporter which logs all finished spans using their String() method, and a CompositeReporter that can be used to combine more than one reporter into one, e.g. to attach a logging reporter to the main remote reporter.

Span Reporting Transports

The remote reporter uses "transports" to actually send the spans out of process. Currently the supported transports include:

Sampling

The tracer does not record all spans, but only those that have the sampling bit set in the flags. When a new trace is started and a new unique ID is generated, a sampling decision is made whether this trace should be sampled. The sampling decision is propagated to all downstream calls via the flags field of the trace context. The following samplers are available:

  1. RemotelyControlledSampler uses one of the other simpler samplers and periodically updates it by polling an external server. This allows dynamic control of the sampling strategies.
  2. ConstSampler always makes the same sampling decision for all trace IDs. it can be configured to either sample all traces, or to sample none.
  3. ProbabilisticSampler uses a fixed sampling rate as a probability for a given trace to be sampled. The actual decision is made by comparing the trace ID with a random number multiplied by the sampling rate.
  4. RateLimitingSampler can be used to allow only a certain fixed number of traces to be sampled per second.

Delayed sampling

Version 2.20 introduced the ability to delay sampling decisions in the life cycle of the root span. It involves several features and architectural changes:

  • Shared sampling state: the sampling state is shared across all local (i.e. in-process) spans for a given trace.
  • New SamplerV2 API allows the sampler to be called at multiple points in the life cycle of a span:
    • on span creation
    • on overwriting span operation name
    • on setting span tags
    • on finishing the span
  • Final/non-final sampling state: the new SamplerV2 API allows the sampler to indicate if the negative sampling decision is final or not (positive sampling decisions are always final). If the decision is not final, the sampler will be called again on further span life cycle events, like setting tags.

These new features are used in the experimental x.TagMatchingSampler, which can sample a trace based on a certain tag added to the root span or one of its local (in-process) children. The sampler can be used with another experimental x.PrioritySampler that allows multiple samplers to try to make a sampling decision, in a certain priority order.

Baggage Injection

The OpenTracing spec allows for baggage, which are key value pairs that are added to the span context and propagated throughout the trace. An external process can inject baggage by setting the special HTTP Header jaeger-baggage on a request:

curl -H "jaeger-baggage: key1=value1, key2=value2" http://myhost.com

Baggage can also be programatically set inside your service:

if span := opentracing.SpanFromContext(ctx); span != nil {
    span.SetBaggageItem("key", "value")
}

Another service downstream of that can retrieve the baggage in a similar way:

if span := opentracing.SpanFromContext(ctx); span != nil {
    val := span.BaggageItem("key")
    println(val)
}

Debug Traces (Forced Sampling)

Programmatically

The OpenTracing API defines a sampling.priority standard tag that can be used to affect the sampling of a span and its children:

import (
    "github.com/opentracing/opentracing-go"
    "github.com/opentracing/opentracing-go/ext"
)

span := opentracing.SpanFromContext(ctx)
ext.SamplingPriority.Set(span, 1)

Via HTTP Headers

Jaeger Tracer also understands a special HTTP Header jaeger-debug-id, which can be set in the incoming request, e.g.

curl -H "jaeger-debug-id: some-correlation-id" http://myhost.com

When Jaeger sees this header in the request that otherwise has no tracing context, it ensures that the new trace started for this request will be sampled in the "debug" mode (meaning it should survive all downsampling that might happen in the collection pipeline), and the root span will have a tag as if this statement was executed:

span.SetTag("jaeger-debug-id", "some-correlation-id")

This allows using Jaeger UI to find the trace by this tag.

Zipkin HTTP B3 compatible header propagation

Jaeger Tracer supports Zipkin B3 Propagation HTTP headers, which are used by a lot of Zipkin tracers. This means that you can use Jaeger in conjunction with e.g. these OpenZipkin tracers.

However it is not the default propagation format, see here how to set it up.

SelfRef

Jaeger Tracer supports an additional span reference type call Self, which was proposed to the OpenTracing Specification (https://github.com/opentracing/specification/issues/81) but not yet accepted. This allows the caller to provide an already created SpanContext when starting a new span. The Self reference bypasses trace and span id generation, as well as sampling decisions (i.e. the sampling bit in the SpanContext.flags must be set appropriately by the caller).

The Self reference supports the following use cases:

  • the ability to provide externally generated trace and span IDs
  • appending data to the same span from different processes, such as loading and continuing spans/traces from offline (ie log-based) storage

Usage requires passing in a SpanContext and the jaeger.Self reference type:

span := tracer.StartSpan(
    "continued_span",
    jaeger.SelfRef(yourSpanContext),
)
...
defer span.Finish()

License

Apache 2.0 License.

# Packages

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Package rpcmetrics implements an Observer that can be used to emit RPC metrics.
No description provided by the author
No description provided by the author
No description provided by the author
Package transport defines various transports that can be used with RemoteReporter to send spans out of process.
No description provided by the author
Package x contains experimental functionality with no guarantees of stable APIs.
Package zipkin comprises Zipkin functionality for Zipkin compatibility.

# Functions

BuildJaegerProcessThrift creates a thrift Process type.
BuildJaegerThrift builds jaeger span based on internal span.
BuildZipkinThrift builds thrift span based on internal span.
ContextFromString reconstructs the Context encoded in a string.
ConvertLogsToJaegerTags converts log Fields into jaeger tags.
EnableFirehose enables firehose flag on the span context.
NewAdaptiveSampler returns a new PerOperationSampler.
NewBinaryPropagator creates a combined Injector and Extractor for Binary format.
NewCompositeReporter creates a reporter that ignores all reported spans.
NewConstSampler creates a ConstSampler.
NewGuaranteedThroughputProbabilisticSampler returns a delegating sampler that applies both ProbabilisticSampler and RateLimitingSampler.
NewHTTPHeaderPropagator creates a combined Injector and Extractor for HTTPHeaders format.
NewInMemoryReporter creates a reporter that stores spans in memory.
NewLoggingReporter creates a reporter that logs all reported spans to provided logger.
NewMetrics creates a new Metrics struct and initializes it.
NewNullMetrics creates a new Metrics struct that won't report any metrics.
NewNullReporter creates a no-op reporter that ignores all reported spans.
NewPerOperationSampler returns a new PerOperationSampler.
NewProbabilisticSampler creates a sampler that randomly samples a certain percentage of traces specified by the samplingRate, in the range between 0.0 and 1.0.
NewRateLimitingSampler creates new RateLimitingSampler.
NewRemotelyControlledSampler creates a sampler that periodically pulls the sampling strategy from an HTTP sampling server (e.g.
NewRemoteReporter creates a new reporter that sends spans out of process by means of Sender.
NewSpanContext creates a new instance of SpanContext.
NewTag creates a new Tag.
NewTextMapPropagator creates a combined Injector and Extractor for TextMap format.
NewTracer creates Tracer implementation that reports tracing to Jaeger.
NewUDPTransport creates a reporter that submits spans to jaeger-agent.
NewUDPTransportWithParams creates a reporter that submits spans to jaeger-agent.
SelfRef creates an opentracing compliant SpanReference from a jaeger SpanContext.
SpanIDFromString creates a SpanID from a hexadecimal string.
TraceIDFromString creates a TraceID from a hexadecimal string.

# Constants

DefaultMaxTagValueLength is the default max length of byte array or string allowed in the tag value.
DefaultSamplingServerPort is the default port to fetch sampling config from, via http.
DefaultUDPSpanServerHost is the default host to send the spans to, via UDP.
DefaultUDPSpanServerPort is the default port to send the spans to, via UDP.
JaegerBaggageHeader is the name of the HTTP header that is used to submit baggage.
JaegerClientVersion is the version of the client library reported as Span tag.
JaegerClientVersionTagKey is the name of the tag used to report client version.
JaegerDebugHeader is the name of HTTP header or a TextMap carrier key which, if found in the carrier, forces the trace to be sampled as "debug" trace.
SamplerParamTagKey reports the parameter of the sampler, like sampling probability.
SamplerTypeConst is the type of sampler that always makes the same decision.
SamplerTypeLowerBound is the type of sampler that samples at least a fixed number of traces per second.
SamplerTypeProbabilistic is the type of sampler that samples traces with a certain fixed probability.
SamplerTypeRateLimiting is the type of sampler that samples only up to a fixed number of traces per second.
SamplerTypeRemote is the type of sampler that polls Jaeger agent for sampling strategy.
SamplerTypeTagKey reports which sampler was used on the root span.
SpanContextFormat is a constant used as OpenTracing Format.
TraceBaggageHeaderPrefix is the prefix for http headers used to propagate baggage.
TraceContextHeaderName is the http header name used to propagate tracing context.
TracerHostnameTagKey used to report host name of the process.
TracerIPTagKey used to report ip of the process.
TracerStateHeaderName is deprecated.
TracerUUIDTagKey used to report UUID of the client process.
ZipkinSpanFormat is an OpenTracing carrier format constant.

# Variables

DefaultSamplingServerURL is the default url to fetch sampling config from, via http.
NullLogger is implementation of the Logger interface that delegates to default `log` package.
ReporterOptions is a factory for all available ReporterOption's.
SamplerOptions is a factory for all available SamplerOption's.
StdLogger is implementation of the Logger interface that delegates to default `log` package.
TracerOptions is a factory for all available TracerOption's.

# Structs

AdaptiveSamplerUpdater is used by RemotelyControlledSampler to parse sampling configuration.
BinaryPropagator is a combined Injector and Extractor for Binary format.
ConstSampler is a sampler that always makes the same decision.
GuaranteedThroughputProbabilisticSampler is a sampler that leverages both ProbabilisticSampler and RateLimitingSampler.
HeadersConfig contains the values for the header keys that Jaeger will use.
InMemoryReporter is used for testing, and simply collects spans in memory.
Metrics is a container of all stats emitted by Jaeger tracer.
PerOperationSampler is a delegating sampler that applies GuaranteedThroughputProbabilisticSampler on a per-operation basis.
PerOperationSamplerParams defines parameters when creating PerOperationSampler.
ProbabilisticSampler is a sampler that randomly samples a certain percentage of traces.
ProbabilisticSamplerUpdater is used by RemotelyControlledSampler to parse sampling configuration.
Process holds process specific metadata that's relevant to this client.
RateLimitingSampler samples at most maxTracesPerSecond.
RateLimitingSamplerUpdater is used by RemotelyControlledSampler to parse sampling configuration.
Reference represents a causal reference to other Spans (via their SpanContext).
RemotelyControlledSampler is a delegating sampler that polls a remote server for the appropriate sampling strategy, constructs a corresponding sampler and delegates to it for sampling decisions.
SamplerOptionsFactory is a factory for all available SamplerOption's.
SamplerV2Base can be used by V2 samplers to implement dummy V1 methods.
SamplingDecision is returned by the V2 samplers.
Span implements opentracing.Span.
SpanContext represents propagated span identity and state.
Tag is a simple key value wrapper.
TextMapPropagator is a combined Injector and Extractor for TextMap format.
TraceID represents unique 128bit identifier of a trace.
Tracer implements opentracing.Tracer.
UDPTransportParams allows specifying options for initializing a UDPTransport.

# Interfaces

ContribObserver can be registered with the Tracer to receive notifications about new Spans.
ContribSpanObserver is created by the Observer and receives notifications about other Span events.
ExtractableZipkinSpan is a type of Carrier used for integration with Zipkin-aware RPC frameworks (like TChannel).
Extractor is responsible for extracting SpanContext instances from a format-specific "carrier" object.
InjectableZipkinSpan is a type of Carrier used for integration with Zipkin-aware RPC frameworks (like TChannel).
Injector is responsible for injecting SpanContext instances in a manner suitable for propagation via a format-specific "carrier" object.
Logger provides an abstract interface for logging from Reporters.
Observer can be registered with the Tracer to receive notifications about new Spans.
ProcessSetter sets a process.
Reporter is called by the tracer when a span is completed to report the span to the tracing collector.
Sampler decides whether a new trace should be sampled or not.
SamplerUpdater is used by RemotelyControlledSampler to apply sampling strategies, retrieved from remote config server, to the current sampler.
SamplerV2 is an extension of the V1 samplers that allows sampling decisions be made at different points of the span lifecycle.
SamplingStrategyFetcher is used to fetch sampling strategy updates from remote server.
SamplingStrategyParser is used to parse sampling strategy updates.
SpanAllocator abstraction of managign span allocations.
SpanObserver is created by the Observer and receives notifications about other Span events.
Transport abstracts the method of sending spans out of process.

# Type aliases

ReporterOption is a function that sets some option on the reporter.
SamplerOption is a function that sets some option on the sampler.
SpanID represents unique 64bit identifier of a span.
TracerOption is a function that sets some option on the tracer.