tracer

package
v2.0.0-...-b084466 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2024 License: Apache-2.0, BSD-3-Clause, Apache-2.0 Imports: 59 Imported by: 102

Documentation

Overview

Package tracer contains Datadog's core tracing client. It is used to trace requests as they flow across web servers, databases and microservices, giving developers visibility into bottlenecks and troublesome requests. To start the tracer, simply call the start method along with an optional set of options. By default, the trace agent is considered to be found at "localhost:8126". In a setup where this would be different (let's say 127.0.0.1:1234), we could do:

tracer.Start(tracer.WithAgentAddr("127.0.0.1:1234"))
defer tracer.Stop()

The tracing client can perform trace sampling. While the trace agent already samples traces to reduce bandwidth usage, client sampling reduces performance overhead. To make use of it, the package comes with a ready-to-use rate sampler that can be passed to the tracer. To use it and keep only 30% of the requests, one would do:

s := tracer.NewRateSampler(0.3)
tracer.Start(tracer.WithSampler(s))

More precise control of sampling rates can be configured using sampling rules. This can be applied based on span name, service or both, and is used to determine the sampling rate to apply. MaxPerSecond specifies max number of spans per second that can be sampled per the rule and applies only to sampling rules of type tracer.SamplingRuleSpan. If MaxPerSecond is not specified, the default is no limit.

rules := []tracer.SamplingRule{
      // sample 10% of traces with the span name "web.request"
      tracer.NameRule("web.request", 0.1),
      // sample 20% of traces for the service "test-service"
      tracer.ServiceRule("test-service", 0.2),
      // sample 30% of traces when the span name is "db.query" and the service
      // is "postgres.db"
      tracer.NameServiceRule("db.query", "postgres.db", 0.3),
      // sample 100% of traces when name and service match these regular expressions
      {Name: regexp.MustCompile("web\\..*"), Service: regexp.MustCompile("^test-"), Rate: 1.0},
      // sample 50% of spans when service and name match these glob patterns with no limit on the number of spans
      tracer.SpanNameServiceRule("web.*", "test-*", 0.5),
      // sample 50% of spans when service and name match these glob patterns up to 100 spans per second
      tracer.SpanNameServiceMPSRule("web.*", "test-*", 0.5, 100),
}
tracer.Start(tracer.WithSamplingRules(rules))
defer tracer.Stop()

Sampling rules can also be configured at runtime using the DD_TRACE_SAMPLING_RULES and DD_SPAN_SAMPLING_RULES environment variables. When set, it overrides rules set by tracer.WithSamplingRules. The value is a JSON array of objects. For trace sampling rules, the "sample_rate" field is required, the "name" and "service" fields are optional. For span sampling rules, the "name" and "service", if specified, must be a valid glob pattern, i.e. a string where "*" matches any contiguous substring, even an empty string, and "?" character matches exactly one of any character. The "sample_rate" field is optional, and if not specified, defaults to "1.0", sampling 100% of the spans. The "max_per_second" field is optional, and if not specified, defaults to 0, keeping all the previously sampled spans.

export DD_TRACE_SAMPLING_RULES='[{"name": "web.request", "sample_rate": 1.0}]'
export DD_SPAN_SAMPLING_RULES='[{"service":"test.?","name": "web.*", "sample_rate": 1.0, "max_per_second":100}]'

To create spans, use the functions StartSpan and StartSpanFromContext. Both accept StartSpanOptions that can be used to configure the span. A span that is started with no parent will begin a new trace. See the function documentation for details on specific usage. Each trace has a hard limit of 100,000 spans, after which the trace will be dropped and give a diagnostic log message. In practice users should not approach this limit as traces of this size are not useful and impossible to visualize.

See the contrib package ( https://pkg.go.dev/github.com/DataDog/dd-trace-go/v2/contrib ) for integrating datadog with various libraries, frameworks and clients.

All spans created by the tracer contain a context hereby referred to as the span context. Note that this is different from Go's context. The span context is used to package essential information from a span, which is needed when creating child spans that inherit from it. Thus, a child span is created from a span's span context. The span context can originate from within the same process, but also a different process or even a different machine in the case of distributed tracing.

To make use of distributed tracing, a span's context may be injected via a carrier into a transport (HTTP, RPC, etc.) to be extracted on the other end and used to create spans that are direct descendants of it. A couple of carrier interfaces which should cover most of the use-case scenarios are readily provided, such as HTTPCarrier and TextMapCarrier. Users are free to create their own, which will work with our propagation algorithm as long as they implement the TextMapReader and TextMapWriter interfaces. An example alternate implementation is the MDCarrier in our gRPC integration.

As an example, injecting a span's context into an HTTP request would look like this. (See the net/http contrib package for more examples https://pkg.go.dev/github.com/DataDog/dd-trace-go/v2/contrib/net/http):

req, err := http.NewRequest("GET", "http://example.com", nil)
// ...
err := tracer.Inject(span.Context(), tracer.HTTPHeadersCarrier(req.Header))
// ...
http.DefaultClient.Do(req)

Then, on the server side, to continue the trace one would do:

sctx, err := tracer.Extract(tracer.HTTPHeadersCarrier(req.Header))
// ...
span := tracer.StartSpan("child.span", tracer.ChildOf(sctx))

In the same manner, any means can be used as a carrier to inject a context into a transport. Go's context can also be used as a means to transport spans within the same process. The methods StartSpanFromContext, ContextWithSpan and SpanFromContext exist for this reason.

Some libraries and frameworks are supported out-of-the-box by using one of our integrations. You can see a list of supported integrations here: https://godoc.org/github.com/DataDog/dd-trace-go/v2/contrib

Example

A basic example demonstrating how to start the tracer, as well as how to create a root span and a child span that is a descendant of it.

// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016 Datadog, Inc.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/DataDog/dd-trace-go/v2/ddtrace/ext"
	"github.com/DataDog/dd-trace-go/v2/ddtrace/tracer"
)

// A basic example demonstrating how to start the tracer, as well as how
// to create a root span and a child span that is a descendant of it.
func main() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	// Start the tracer and defer the Stop method.
	tracer.Start()
	defer tracer.Stop()

	// Start a root span.
	span, ctx := tracer.StartSpanFromContext(ctx, "parent")
	defer span.Finish()

	// Run some code.
	err := doSomething(ctx)
	if err != nil {
		panic(err)
	}
}

func doSomething(ctx context.Context) (err error) {
	// Create a child, using the context of the parent span.
	span, ctx := tracer.StartSpanFromContext(ctx, "do.something", tracer.Tag(ext.ResourceName, "alarm"))
	defer func() {
		span.Finish(tracer.WithError(err))
	}()

	// Perform an operation.
	select {
	case <-time.After(5 * time.Millisecond):
		fmt.Println("ding!")
	case <-ctx.Done():
		fmt.Println("timed out :(")
	}
	return ctx.Err()
}
Output:

Index

Examples

Constants

View Source
const (
	Local    provenance = iota
	Customer provenance = 1
	Dynamic  provenance = 2
)
View Source
const (
	SamplingRuleUndefined SamplingRuleType = 0

	// SamplingRuleTrace specifies a sampling rule that applies to the entire trace if any spans satisfy the criteria.
	// If a sampling rule is of type SamplingRuleTrace, such rule determines the sampling rate to apply
	// to trace spans. If a span matches that rule, it will impact the trace sampling decision.
	SamplingRuleTrace = iota

	// SamplingRuleSpan specifies a sampling rule that applies to a single span without affecting the entire trace.
	// If a sampling rule is of type SamplingRuleSingleSpan, such rule determines the sampling rate to apply
	// to individual spans. If a span matches a rule, it will NOT impact the trace sampling decision.
	// In the case that a trace is dropped and thus not sent to the Agent, spans kept on account
	// of matching SamplingRuleSingleSpan rules must be conveyed separately.
	SamplingRuleSpan
)
View Source
const (
	// DefaultBaggageHeaderPrefix specifies the prefix that will be used in
	// HTTP headers or text maps to prefix baggage keys.
	DefaultBaggageHeaderPrefix = "ot-baggage-"

	// DefaultTraceIDHeader specifies the key that will be used in HTTP headers
	// or text maps to store the trace ID.
	DefaultTraceIDHeader = "x-datadog-trace-id"

	// DefaultParentIDHeader specifies the key that will be used in HTTP headers
	// or text maps to store the parent ID.
	DefaultParentIDHeader = "x-datadog-parent-id"

	// DefaultPriorityHeader specifies the key that will be used in HTTP headers
	// or text maps to store the sampling priority value.
	DefaultPriorityHeader = "x-datadog-sampling-priority"
)
View Source
const TraceIDZero string = "00000000000000000000000000000000"

Variables

View Source
var (
	// ErrInvalidCarrier is returned when the carrier provided to the propagator
	// does not implement the correct interfaces.
	ErrInvalidCarrier = errors.New("invalid carrier")

	// ErrInvalidSpanContext is returned when the span context found in the
	// carrier is not of the expected type.
	ErrInvalidSpanContext = errors.New("invalid span context")

	// ErrSpanContextCorrupted is returned when there was a problem parsing
	// the information found in the carrier.
	ErrSpanContextCorrupted = errors.New("span context corrupted")

	// ErrSpanContextNotFound represents missing information in the given carrier.
	ErrSpanContextNotFound = errors.New("span context not found")
)

Functions

func ContextWithSpan

func ContextWithSpan(ctx context.Context, s *Span) context.Context

ContextWithSpan returns a copy of the given context which includes the span s.

func EqualsFalseNegative

func EqualsFalseNegative(a, b []SamplingRule) bool

Tests whether two sets of the rules are the same. This returns result that can be false negative. If the result is true, then the two sets of rules are guaranteed to be the same. On the other hand, false can be returned while the two rulesets are logically the same. This function can be used to detect optimization opportunities when two rulesets are the same. For example, an update of one ruleset is not needed if it's the same as the previous one.

func Flush

func Flush()

Flush flushes any buffered traces. Flush is in effect only if a tracer is started. Users do not have to call Flush in order to ensure that traces reach Datadog. It is a convenience method dedicated to a specific use case described below.

Flush is of use in Lambda environments, where starting and stopping the tracer on each invocation may create too much latency. In this scenario, a tracer may be started and stopped by the parent process whereas the invocation can make use of Flush to ensure any created spans reach the agent.

func Inject

func Inject(ctx *SpanContext, carrier interface{}) error

Inject injects the given SpanContext into the carrier. The carrier is expected to implement TextMapWriter, otherwise an error is returned. If the tracer is not started, calling this function is a no-op.

func MarkIntegrationImported

func MarkIntegrationImported(integration string) bool

MarkIntegrationImported labels the given integration as imported

func SetDataStreamsCheckpoint

func SetDataStreamsCheckpoint(ctx context.Context, edgeTags ...string) (outCtx context.Context, ok bool)

SetDataStreamsCheckpoint sets a consume or produce checkpoint in a Data Streams pathway. This enables tracking data flow & end to end latency. To learn more about the data streams product, see: https://docs.datadoghq.com/data_streams/go/

func SetDataStreamsCheckpointWithParams

func SetDataStreamsCheckpointWithParams(ctx context.Context, params options.CheckpointParams, edgeTags ...string) (outCtx context.Context, ok bool)

SetDataStreamsCheckpointWithParams sets a consume or produce checkpoint in a Data Streams pathway. This enables tracking data flow & end to end latency. To learn more about the data streams product, see: https://docs.datadoghq.com/data_streams/go/

func SetGlobalTracer

func SetGlobalTracer(t Tracer)

SetGlobalTracer sets the global tracer to t.

func SetUser

func SetUser(s *Span, id string, opts ...UserMonitoringOption)

SetUser associates user information to the current trace which the provided span belongs to. The options can be used to tune which user bit of information gets monitored. In case of distributed traces, the user id can be propagated across traces using the WithPropagation() option. See https://docs.datadoghq.com/security_platform/application_security/setup_and_configure/?tab=set_user#add-user-information-to-traces

func Start

func Start(opts ...StartOption) error

Start starts the tracer with the given set of options. It will stop and replace any running tracer, meaning that calling it several times will result in a restart of the tracer by replacing the current instance with a new one.

func Stop

func Stop()

Stop stops the started tracer. Subsequent calls are valid but become no-op.

func StopTestTracer

func StopTestTracer()

func TrackKafkaCommitOffset

func TrackKafkaCommitOffset(group, topic string, partition int32, offset int64)

TrackKafkaCommitOffset should be used in the consumer, to track when it acks offset. if used together with TrackKafkaProduceOffset it can generate a Kafka lag in seconds metric.

func TrackKafkaHighWatermarkOffset

func TrackKafkaHighWatermarkOffset(cluster string, topic string, partition int32, offset int64)

TrackKafkaHighWatermarkOffset should be used in the producer, to track when it produces a message. if used together with TrackKafkaCommitOffset it can generate a Kafka lag in seconds metric.

func TrackKafkaProduceOffset

func TrackKafkaProduceOffset(topic string, partition int32, offset int64)

TrackKafkaProduceOffset should be used in the producer, to track when it produces a message. if used together with TrackKafkaCommitOffset it can generate a Kafka lag in seconds metric.

func UseLogger

func UseLogger(l Logger)

UseLogger sets l as the logger for all tracer and profiler logs.

Types

type Chunk

type Chunk struct {
	// TODO:(kjn v2) Should probably not be public, or be a different type.
	Spans []*Span
	// contains filtered or unexported fields
}

Chunk holds information about a trace Chunk to be flushed, including its spans. The Chunk may be a fully finished local trace Chunk, or only a portion of the local trace Chunk in the case of partial flushing.

type DBMPropagationMode

type DBMPropagationMode string

DBMPropagationMode represents the mode of dbm propagation.

Note that enabling sql comment propagation results in potentially confidential data (service names) being stored in the databases which can then be accessed by other 3rd parties that have been granted access to the database.

const (
	// DBMPropagationModeUndefined represents the dbm propagation mode not being set. This is the same as DBMPropagationModeDisabled.
	DBMPropagationModeUndefined DBMPropagationMode = ""
	// DBMPropagationModeDisabled represents the dbm propagation mode where all propagation is disabled.
	DBMPropagationModeDisabled DBMPropagationMode = "disabled"
	// DBMPropagationModeService represents the dbm propagation mode where only service tags (name, env, version) are propagated to dbm.
	DBMPropagationModeService DBMPropagationMode = "service"
	// DBMPropagationModeFull represents the dbm propagation mode where both service tags and tracing tags are propagated. Tracing tags include span id, trace id and the sampled flag.
	DBMPropagationModeFull DBMPropagationMode = "full"
)

type FinishConfig

type FinishConfig struct {
	// FinishTime represents the time that should be set as finishing time for the
	// span. Implementations should use the current time when FinishTime.IsZero().
	FinishTime time.Time

	// Error holds an optional error that should be set on the span before
	// finishing.
	Error error

	// NoDebugStack will prevent any set errors from generating an attached stack trace tag.
	NoDebugStack bool

	// StackFrames specifies the number of stack frames to be attached in spans that finish with errors.
	StackFrames uint

	// SkipStackFrames specifies the offset at which to start reporting stack frames from the stack.
	SkipStackFrames uint
}

FinishConfig holds the configuration for finishing a span. It is usually passed around by reference to one or more FinishOption functions which shape it into its final form.

type FinishOption

type FinishOption func(cfg *FinishConfig)

FinishOption is a configuration option that can be used with a Span's Finish method.

func FinishTime

func FinishTime(t time.Time) FinishOption

FinishTime sets the given time as the finishing time for the span. By default, the current time is used.

func NoDebugStack

func NoDebugStack() FinishOption

NoDebugStack prevents any error presented using the WithError finishing option from generating a stack trace. This is useful in situations where errors are frequent and performance is critical.

func StackFrames

func StackFrames(n, skip uint) FinishOption

StackFrames limits the number of stack frames included into erroneous spans to n, starting from skip.

func WithError

func WithError(err error) FinishOption

WithError marks the span as having had an error. It uses the information from err to set tags such as the error message, error type and stack trace. It has no effect if the error is nil.

func WithFinishConfig

func WithFinishConfig(cfg *FinishConfig) FinishOption

WithFinishConfig merges the given FinishConfig into the one used to finish the span. It is useful when you want to set a common base finish config, reducing the number of function calls in hot loops.

type HTTPHeadersCarrier

type HTTPHeadersCarrier http.Header

HTTPHeadersCarrier wraps an http.Header as a TextMapWriter and TextMapReader, allowing it to be used using the provided Propagator implementation.

func (HTTPHeadersCarrier) ForeachKey

func (c HTTPHeadersCarrier) ForeachKey(handler func(key, val string) error) error

ForeachKey implements TextMapReader.

func (HTTPHeadersCarrier) Set

func (c HTTPHeadersCarrier) Set(key, val string)

Set implements TextMapWriter.

type LogLevel

type LogLevel = log.Level

LogLevel represents the logging level that the log package prints at.

type Logger

type Logger interface {
	// Log prints the given message.
	Log(msg string)
}

Logger implementations are able to log given messages that the tracer or profiler might output.

func AdaptLogger

func AdaptLogger(fn func(lvl LogLevel, msg string, a ...any)) Logger

AdaptLogger adapts a function to the Logger interface to adapt any logger to the Logger interface.

type NoopTracer

type NoopTracer struct{}

NoopTracer is an implementation of Tracer that is a no-op.

func (NoopTracer) Extract

func (NoopTracer) Extract(_ interface{}) (*SpanContext, error)

Extract implements Tracer.

func (NoopTracer) Flush

func (NoopTracer) Flush()

func (NoopTracer) Inject

func (NoopTracer) Inject(_ *SpanContext, _ interface{}) error

Inject implements Tracer.

func (NoopTracer) SetServiceInfo

func (NoopTracer) SetServiceInfo(_, _, _ string)

SetServiceInfo implements Tracer.

func (NoopTracer) StartSpan

func (NoopTracer) StartSpan(_ string, _ ...StartSpanOption) *Span

StartSpan implements Tracer.

func (NoopTracer) Stop

func (NoopTracer) Stop()

Stop implements Tracer.

func (NoopTracer) SubmitAbandonedSpan

func (NoopTracer) SubmitAbandonedSpan(*Span, bool)

func (NoopTracer) SubmitChunk

func (NoopTracer) SubmitChunk(any)

func (NoopTracer) SubmitStats

func (NoopTracer) SubmitStats(*Span)

func (NoopTracer) TracerConf

func (NoopTracer) TracerConf() TracerConf

TODO(kjn v2): These should be removed. They are here temporarily to facilitate the shift to the v2 API.

type Propagator

type Propagator interface {
	// Inject takes the SpanContext and injects it into the carrier.
	Inject(context *SpanContext, carrier interface{}) error

	// Extract returns the SpanContext from the given carrier.
	Extract(carrier interface{}) (*SpanContext, error)
}

Propagator implementations should be able to inject and extract SpanContexts into an implementation specific carrier.

func NewPropagator

func NewPropagator(cfg *PropagatorConfig, propagators ...Propagator) Propagator

NewPropagator returns a new propagator which uses TextMap to inject and extract values. It propagates trace and span IDs and baggage. To use the defaults, nil may be provided in place of the config.

The inject and extract propagators are determined using environment variables with the following order of precedence:

  1. DD_TRACE_PROPAGATION_STYLE_INJECT
  2. DD_PROPAGATION_STYLE_INJECT (deprecated)
  3. DD_TRACE_PROPAGATION_STYLE (applies to both inject and extract)
  4. If none of the above, use default values

type PropagatorConfig

type PropagatorConfig struct {
	// BaggagePrefix specifies the prefix that will be used to store baggage
	// items in a map. It defaults to DefaultBaggageHeaderPrefix.
	BaggagePrefix string

	// TraceHeader specifies the map key that will be used to store the trace ID.
	// It defaults to DefaultTraceIDHeader.
	TraceHeader string

	// ParentHeader specifies the map key that will be used to store the parent ID.
	// It defaults to DefaultParentIDHeader.
	ParentHeader string

	// PriorityHeader specifies the map key that will be used to store the sampling priority.
	// It defaults to DefaultPriorityHeader.
	PriorityHeader string

	// MaxTagsHeaderLen specifies the maximum length of trace tags header value.
	// It defaults to defaultMaxTagsHeaderLen, a value of 0 disables propagation of tags.
	MaxTagsHeaderLen int

	// B3 specifies if B3 headers should be added for trace propagation.
	// See https://github.com/openzipkin/b3-propagation
	B3 bool
}

PropagatorConfig defines the configuration for initializing a propagator.

type RateSampler

type RateSampler interface {
	Sampler

	// Rate returns the current sample rate.
	Rate() float64

	// SetRate sets a new sample rate.
	SetRate(rate float64)
}

RateSampler is a sampler implementation which randomly selects spans using a provided rate. For example, a rate of 0.75 will permit 75% of the spans. RateSampler implementations should be safe for concurrent use.

func NewAllSampler

func NewAllSampler() RateSampler

NewAllSampler is a short-hand for NewRateSampler(1). It is all-permissive.

func NewRateSampler

func NewRateSampler(rate float64) RateSampler

NewRateSampler returns an initialized RateSampler with a given sample rate.

type Rule

type Rule struct {
	ServiceGlob  string
	NameGlob     string
	ResourceGlob string
	Tags         map[string]string // map of string to glob pattern
	Rate         float64
	MaxPerSecond float64
}

Rule is used to create a sampling rule.

type SQLCommentCarrier

type SQLCommentCarrier struct {
	Query          string
	Mode           DBMPropagationMode
	DBServiceName  string
	SpanID         uint64
	PeerDBHostname string
	PeerDBName     string
}

SQLCommentCarrier is a carrier implementation that injects a span context in a SQL query in the form of a sqlcommenter formatted comment prepended to the original query text. See https://google.github.io/sqlcommenter/spec/ for more details.

func (*SQLCommentCarrier) Extract

func (c *SQLCommentCarrier) Extract() (*SpanContext, error)

Extract parses for key value attributes in a sql query injected with trace information in order to build a span context

func (*SQLCommentCarrier) Inject

func (c *SQLCommentCarrier) Inject(ctx *SpanContext) error

Inject injects a span context in the carrier's Query field as a comment.

type Sampler

type Sampler interface {
	// Sample returns true if the given span should be sampled.
	Sample(span *Span) bool
}

Sampler is an interface for sampling traces.

type SamplingRule

type SamplingRule struct {
	// Service specifies the regex pattern that a span service name must match.
	Service *regexp.Regexp

	// Name specifies the regex pattern that a span operation name must match.
	Name *regexp.Regexp

	// Rate specifies the sampling rate that should be applied to spans that match
	// service and/or name of the rule.
	Rate float64

	// MaxPerSecond specifies max number of spans per second that can be sampled per the rule.
	// If not specified, the default is no limit.
	MaxPerSecond float64

	// Resource specifies the regex pattern that a span resource must match.
	Resource *regexp.Regexp

	// Tags specifies the map of key-value patterns that span tags must match.
	Tags map[string]*regexp.Regexp

	Provenance provenance
	// contains filtered or unexported fields
}

SamplingRule is used for applying sampling rates to spans that match the service name, operation name or both. For basic usage, consider using the helper functions ServiceRule, NameRule, etc.

func SpanSamplingRules

func SpanSamplingRules(rules ...Rule) []SamplingRule

SpanSamplingRules creates a sampling rule that applies to a single span without affecting the entire trace.

func TraceSamplingRules

func TraceSamplingRules(rules ...Rule) []SamplingRule

TraceSamplingRules creates a sampling rule that applies to the entire trace if any spans satisfy the criteria.

func (*SamplingRule) EqualsFalseNegative

func (sr *SamplingRule) EqualsFalseNegative(other *SamplingRule) bool

func (SamplingRule) MarshalJSON

func (sr SamplingRule) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (SamplingRule) String

func (sr SamplingRule) String() string

func (*SamplingRule) UnmarshalJSON

func (sr *SamplingRule) UnmarshalJSON(b []byte) error

type SamplingRuleType

type SamplingRuleType int

SamplingRuleType represents a type of sampling rule spans are matched against.

func (SamplingRuleType) String

func (sr SamplingRuleType) String() string

type Span

type Span struct {
	sync.RWMutex `msg:"-"` // all fields are protected by this RWMutex
	// contains filtered or unexported fields
}

Span represents a computation. Callers must call Finish when a Span is complete to ensure it's submitted.

func SpanFromContext

func SpanFromContext(ctx context.Context) (*Span, bool)

SpanFromContext returns the span contained in the given context. A second return value indicates if a span was found in the context. If no span is found, a no-op span is returned.

func SpanStart

func SpanStart(operationName string, options ...StartSpanOption) *Span

func StartSpan

func StartSpan(operationName string, opts ...StartSpanOption) *Span

StartSpan starts a new span with the given operation name and set of options. If the tracer is not started, calling this function is a no-op.

func StartSpanFromContext

func StartSpanFromContext(ctx context.Context, operationName string, opts ...StartSpanOption) (*Span, context.Context)

StartSpanFromContext returns a new span with the given operation name and options. If a span is found in the context, it will be used as the parent of the resulting span. If the ChildOf option is passed, it will only be used as the parent if there is no span found in `ctx`.

func (s *Span) AddLink(spanContext *SpanContext, attributes map[string]string)

AddLink sets a casuality link to another span via a spanContext. It also stores details about the link in an attributes map.

func (*Span) AsMap

func (s *Span) AsMap() map[string]interface{}

AsMap places tags and span properties into a map and returns it.

Note that this is not performant, nor are spans guaranteed to have all of their properties set at any time during normal operation! This is used for testing only, and should not be used in non-test code, or you may run into performance or other issues.

func (*Span) BaggageItem

func (s *Span) BaggageItem(key string) string

BaggageItem gets the value for a baggage item given its key. Returns the empty string if the value isn't found in this Span.

func (*Span) Context

func (s *Span) Context() *SpanContext

Context yields the SpanContext for this Span. Note that the return value of Context() is still valid after a call to Finish(). This is called the span context and it is different from Go's context.

func (*Span) DecodeMsg

func (z *Span) DecodeMsg(dc *msgp.Reader) (err error)

DecodeMsg implements msgp.Decodable

func (*Span) EncodeMsg

func (z *Span) EncodeMsg(en *msgp.Writer) (err error)

EncodeMsg implements msgp.Encodable

func (*Span) Finish

func (s *Span) Finish(opts ...FinishOption)

Finish closes this Span (but not its children) providing the duration of its part of the tracing session.

func (*Span) Format

func (s *Span) Format(f fmt.State, c rune)

Format implements fmt.Formatter.

func (*Span) Msgsize

func (z *Span) Msgsize() (s int)

Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message

func (*Span) Root

func (s *Span) Root() *Span

root returns the root span of the span's trace. The return value shouldn't be nil as long as the root span is valid and not finished.

func (*Span) SetBaggageItem

func (s *Span) SetBaggageItem(key, val string)

SetBaggageItem sets a key/value pair as baggage on the span. Baggage items are propagated down to descendant spans and injected cross-process. Use with care as it adds extra load onto your tracing layer.

func (*Span) SetOperationName

func (s *Span) SetOperationName(operationName string)

SetOperationName sets or changes the operation name.

func (*Span) SetTag

func (s *Span) SetTag(key string, value interface{})

SetTag adds a set of key/value metadata to the span.

func (*Span) SetUser

func (s *Span) SetUser(id string, opts ...UserMonitoringOption)

SetUser associates user information to the current trace which the provided span belongs to. The options can be used to tune which user bit of information gets monitored. In case of distributed traces, the user id can be propagated across traces using the WithPropagation() option. See https://docs.datadoghq.com/security_platform/application_security/setup_and_configure/?tab=set_user#add-user-information-to-traces

func (*Span) StartChild

func (s *Span) StartChild(operationName string, opts ...StartSpanOption) *Span

StartChild starts a new child span with the given operation name and options.

func (*Span) String

func (s *Span) String() string

String returns a human readable representation of the span. Not for production, just debugging.

type SpanContext

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

SpanContext represents a span state that can propagate to descendant spans and across process boundaries. It contains all the information needed to spawn a direct descendant of the span that it belongs to. It can be used to create distributed tracing by propagating it using the provided interfaces.

func Extract

func Extract(carrier interface{}) (*SpanContext, error)

Extract extracts a SpanContext from the carrier. The carrier is expected to implement TextMapReader, otherwise an error is returned. If the tracer is not started, calling this function is a no-op.

func FromGenericCtx

func FromGenericCtx(c ddtrace.SpanContext) *SpanContext

FromGenericCtx converts a ddtrace.SpanContext to a *SpanContext, which can be used to start child spans.

func (*SpanContext) ForeachBaggageItem

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

ForeachBaggageItem implements ddtrace.SpanContext.

func (*SpanContext) SamplingPriority

func (c *SpanContext) SamplingPriority() (p int, ok bool)

func (*SpanContext) SpanID

func (c *SpanContext) SpanID() uint64

SpanID implements ddtrace.SpanContext.

func (*SpanContext) TraceID

func (c *SpanContext) TraceID() string

TraceID implements ddtrace.SpanContext.

func (*SpanContext) TraceIDBytes

func (c *SpanContext) TraceIDBytes() [16]byte

TraceIDBytes implements ddtrace.SpanContext.

func (*SpanContext) TraceIDLower

func (c *SpanContext) TraceIDLower() uint64

TraceIDLower implements ddtrace.SpanContext.

type SpanLink struct {
	// TraceID represents the low 64 bits of the linked span's trace id. This field is required.
	TraceID uint64 `msg:"trace_id" json:"trace_id"`
	// TraceIDHigh represents the high 64 bits of the linked span's trace id. This field is only set if the linked span's trace id is 128 bits.
	TraceIDHigh uint64 `msg:"trace_id_high,omitempty" json:"trace_id_high"`
	// SpanID represents the linked span's span id.
	SpanID uint64 `msg:"span_id" json:"span_id"`
	// Attributes is a mapping of keys to string values. These values are used to add additional context to the span link.
	Attributes map[string]string `msg:"attributes,omitempty" json:"attributes"`
	// Tracestate is the tracestate of the linked span. This field is optional.
	Tracestate string `msg:"tracestate,omitempty" json:"tracestate"`
	// Flags represents the W3C trace flags of the linked span. This field is optional.
	Flags uint32 `msg:"flags,omitempty" json:"flags"`
}

func (*SpanLink) DecodeMsg

func (z *SpanLink) DecodeMsg(dc *msgp.Reader) (err error)

DecodeMsg implements msgp.Decodable

func (*SpanLink) EncodeMsg

func (z *SpanLink) EncodeMsg(en *msgp.Writer) (err error)

EncodeMsg implements msgp.Encodable

func (*SpanLink) Msgsize

func (z *SpanLink) Msgsize() (s int)

Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message

type StartOption

type StartOption func(*config)

StartOption represents a function that can be provided as a parameter to Start.

func WithAgentAddr

func WithAgentAddr(addr string) StartOption

WithAgentAddr sets the address where the agent is located. The default is localhost:8126. It should contain both host and port.

func WithAgentURL

func WithAgentURL(agentURL string) StartOption

WithAgentURL sets the full trace agent URL

func WithAnalytics

func WithAnalytics(on bool) StartOption

WithAnalytics allows specifying whether Trace Search & Analytics should be enabled for integrations.

func WithAnalyticsRate

func WithAnalyticsRate(rate float64) StartOption

WithAnalyticsRate sets the global sampling rate for sampling APM events.

func WithDebugMode

func WithDebugMode(enabled bool) StartOption

WithDebugMode enables debug mode on the tracer, resulting in more verbose logging.

func WithDebugSpansMode

func WithDebugSpansMode(timeout time.Duration) StartOption

WithDebugSpansMode enables debugging old spans that may have been abandoned, which may prevent traces from being set to the Datadog Agent, especially if partial flushing is off. This setting can also be configured by setting DD_TRACE_DEBUG_ABANDONED_SPANS to true. The timeout will default to 10 minutes, unless overwritten by DD_TRACE_ABANDONED_SPAN_TIMEOUT. This feature is disabled by default. Turning on this debug mode may be expensive, so it should only be enabled for debugging purposes.

func WithDebugStack

func WithDebugStack(enabled bool) StartOption

WithDebugStack can be used to globally enable or disable the collection of stack traces when spans finish with errors. It is enabled by default. This is a global version of the NoDebugStack FinishOption.

func WithDogstatsdAddress

func WithDogstatsdAddress(addr string) StartOption

WithDogstatsdAddress specifies the address to connect to for sending metrics to the Datadog Agent. It should be a "host:port" string, or the path to a unix domain socket.If not set, it attempts to determine the address of the statsd service according to the following rules:

  1. Look for /var/run/datadog/dsd.socket and use it if present. IF NOT, continue to #2.
  2. The host is determined by DD_AGENT_HOST, and defaults to "localhost"
  3. The port is retrieved from the agent. If not present, it is determined by DD_DOGSTATSD_PORT, and defaults to 8125

This option is in effect when WithRuntimeMetrics is enabled.

func WithEnv

func WithEnv(env string) StartOption

WithEnv sets the environment to which all traces started by the tracer will be submitted. The default value is the environment variable DD_ENV, if it is set.

func WithFeatureFlags

func WithFeatureFlags(feats ...string) StartOption

WithFeatureFlags specifies a set of feature flags to enable. Please take into account that most, if not all features flags are considered to be experimental and result in unexpected bugs.

func WithGlobalServiceName

func WithGlobalServiceName(enabled bool) StartOption

WithGlobalServiceName causes contrib libraries to use the global service name and not any locally defined service name. This is synonymous with `DD_TRACE_REMOVE_INTEGRATION_SERVICE_NAMES_ENABLED`.

func WithGlobalTag

func WithGlobalTag(k string, v interface{}) StartOption

WithGlobalTag sets a key/value pair which will be set as a tag on all spans created by tracer. This option may be used multiple times.

func WithHTTPClient

func WithHTTPClient(client *http.Client) StartOption

WithHTTPClient specifies the HTTP client to use when emitting spans to the agent.

func WithHeaderTags

func WithHeaderTags(headerAsTags []string) StartOption

WithHeaderTags enables the integration to attach HTTP request headers as span tags. Warning: Using this feature can risk exposing sensitive data such as authorization tokens to Datadog. Special headers can not be sub-selected. E.g., an entire Cookie header would be transmitted, without the ability to choose specific Cookies.

func WithHostname

func WithHostname(name string) StartOption

WithHostname allows specifying the hostname with which to mark outgoing traces.

func WithLambdaMode

func WithLambdaMode(enabled bool) StartOption

WithLambdaMode enables lambda mode on the tracer, for use with AWS Lambda. This option is only required if the the Datadog Lambda Extension is not running.

func WithLogStartup

func WithLogStartup(enabled bool) StartOption

WithLogStartup allows enabling or disabling the startup log.

func WithLogger

func WithLogger(logger Logger) StartOption

WithLogger sets logger as the tracer's error printer. Diagnostic and startup tracer logs are prefixed to simplify the search within logs. If JSON logging format is required, it's possible to wrap tracer logs using an existing JSON logger with this function. To learn more about this possibility, please visit: https://github.com/DataDog/dd-trace-go/issues/2152#issuecomment-1790586933

func WithOrchestrion

func WithOrchestrion(metadata map[string]string) StartOption

WithOrchestrion configures Orchestrion's auto-instrumentation metadata. This option is only intended to be used by Orchestrion https://github.com/DataDog/orchestrion

func WithPartialFlushing

func WithPartialFlushing(numSpans int) StartOption

WithPartialFlushing enables flushing of partially finished traces. This is done after "numSpans" have finished in a single local trace at which point all finished spans in that trace will be flushed, freeing up any memory they were consuming. This can also be configured by setting DD_TRACE_PARTIAL_FLUSH_ENABLED to true, which will default to 1000 spans unless overriden with DD_TRACE_PARTIAL_FLUSH_MIN_SPANS. Partial flushing is disabled by default.

func WithPeerServiceDefaults

func WithPeerServiceDefaults(enabled bool) StartOption

WithPeerServiceDefaults sets default calculation for peer.service. Related documentation: https://docs.datadoghq.com/tracing/guide/inferred-service-opt-in/?tab=go#apm-tracer-configuration

func WithPeerServiceMapping

func WithPeerServiceMapping(from, to string) StartOption

WithPeerServiceMapping determines the value of the peer.service tag "from" to be renamed to service "to".

func WithProfilerCodeHotspots

func WithProfilerCodeHotspots(enabled bool) StartOption

WithProfilerCodeHotspots enables the code hotspots integration between the tracer and profiler. This is done by automatically attaching pprof labels called "span id" and "local root span id" when new spans are created. You should not use these label names in your own code when this is enabled. The enabled value defaults to the value of the DD_PROFILING_CODE_HOTSPOTS_COLLECTION_ENABLED env variable or true.

func WithProfilerEndpoints

func WithProfilerEndpoints(enabled bool) StartOption

WithProfilerEndpoints enables the endpoints integration between the tracer and profiler. This is done by automatically attaching a pprof label called "trace endpoint" holding the resource name of the top-level service span if its type is "http", "rpc" or "" (default). You should not use this label name in your own code when this is enabled. The enabled value defaults to the value of the DD_PROFILING_ENDPOINT_COLLECTION_ENABLED env variable or true.

func WithPropagator

func WithPropagator(p Propagator) StartOption

WithPropagator sets an alternative propagator to be used by the tracer.

func WithRuntimeMetrics

func WithRuntimeMetrics() StartOption

WithRuntimeMetrics enables automatic collection of runtime metrics every 10 seconds.

func WithSampler

func WithSampler(s Sampler) StartOption

WithSampler sets the given sampler to be used with the tracer. By default an all-permissive sampler is used. Deprecated: Use WithSamplerRate instead. Custom sampling will be phased out in a future release.

func WithSamplerRate

func WithSamplerRate(rate float64) StartOption

WithRateSampler sets the given sampler rate to be used with the tracer. The rate must be between 0 and 1. By default an all-permissive sampler rate (1) is used.

func WithSamplingRules

func WithSamplingRules(rules []SamplingRule) StartOption

WithSamplingRules specifies the sampling rates to apply to spans based on the provided rules.

func WithSendRetries

func WithSendRetries(retries int) StartOption

WithSendRetries enables re-sending payloads that are not successfully submitted to the agent. This will cause the tracer to retry the send at most `retries` times.

func WithService

func WithService(name string) StartOption

WithService sets the default service name for the program.

func WithServiceMapping

func WithServiceMapping(from, to string) StartOption

WithServiceMapping determines service "from" to be renamed to service "to". This option is is case sensitive and can be used multiple times.

func WithServiceVersion

func WithServiceVersion(version string) StartOption

WithServiceVersion specifies the version of the service that is running. This will be included in spans from this service in the "version" tag, provided that span service name and config service name match. Do NOT use with WithUniversalVersion.

func WithStatsComputation

func WithStatsComputation(enabled bool) StartOption

WithStatsComputation enables client-side stats computation, allowing the tracer to compute stats from traces. This can reduce network traffic to the Datadog Agent, and produce more accurate stats data. This can also be configured by setting DD_TRACE_STATS_COMPUTATION_ENABLED to true. Client-side stats is off by default.

func WithTestDefaults

func WithTestDefaults(statsdClient any) StartOption

WithTestDefaults configures the tracer to not send spans to the agent, and to not collect metrics. Warning: This option should only be used in tests, as it will prevent the tracer from sending spans to the agent.

func WithTraceEnabled

func WithTraceEnabled(enabled bool) StartOption

WithTraceEnabled allows specifying whether tracing will be enabled

func WithUDS

func WithUDS(socketPath string) StartOption

WithUDS configures the HTTP client to dial the Datadog Agent via the specified Unix Domain Socket path.

func WithUniversalVersion

func WithUniversalVersion(version string) StartOption

WithUniversalVersion specifies the version of the service that is running, and will be applied to all spans, regardless of whether span service name and config service name match. See: WithService, WithServiceVersion. Do NOT use with WithServiceVersion.

type StartSpanConfig

type StartSpanConfig struct {
	// Parent holds the SpanContext that should be used as a parent for the
	// new span. If nil, implementations should return a root span.
	Parent *SpanContext

	// StartTime holds the time that should be used as the start time of the span.
	// Implementations should use the current time when StartTime.IsZero().
	StartTime time.Time

	// Tags holds a set of key/value pairs that should be set as metadata on the
	// new span.
	Tags map[string]interface{}

	// SpanID will be the SpanID of the Span, overriding the random number that would
	// be generated. If no Parent SpanContext is present, then this will also set the
	// TraceID to the same value.
	SpanID uint64

	// Context is the parent context where the span should be stored.
	Context context.Context

	// SpanLink represents a causal relationship between two spans. A span can have multiple links.
	SpanLinks []SpanLink
}

StartSpanConfig holds the configuration for starting a new span. It is usually passed around by reference to one or more StartSpanOption functions which shape it into its final form.

func NewStartSpanConfig

func NewStartSpanConfig(opts ...StartSpanOption) *StartSpanConfig

NewStartSpanConfig allows to build a base config struct. It accepts the same options as StartSpan. It's useful to reduce the number of operations in any hot path and update it for request/operation specifics.

type StartSpanOption

type StartSpanOption func(cfg *StartSpanConfig)

StartSpanOption is a configuration option that can be used with a Tracer's StartSpan method.

func AnalyticsRate

func AnalyticsRate(rate float64) StartSpanOption

AnalyticsRate sets a custom analytics rate for a span. It decides the percentage of events that will be picked up by the App Analytics product. It's represents a float64 between 0 and 1 where 0.5 would represent 50% of events.

func ChildOf deprecated

func ChildOf(ctx *SpanContext) StartSpanOption

ChildOf tells StartSpan to use the given span context as a parent for the created span.

Deprecated: Use span.StartChild instead.

func Measured

func Measured() StartSpanOption

Measured marks this span to be measured for metrics and stats calculations.

func ResourceName

func ResourceName(name string) StartSpanOption

ResourceName sets the given resource name on the started span. A resource could be an SQL query, a URL, an RPC method or something else.

func ServiceName

func ServiceName(name string) StartSpanOption

ServiceName sets the given service name on the started span. For example "http.server".

func SpanType

func SpanType(name string) StartSpanOption

SpanType sets the given span type on the started span. Some examples in the case of the Datadog APM product could be "web", "db" or "cache".

func StartTime

func StartTime(t time.Time) StartSpanOption

StartTime sets a custom time as the start time for the created span. By default a span is started using the creation time.

func Tag

func Tag(k string, v interface{}) StartSpanOption

Tag sets the given key/value pair as a tag on the started Span.

func WithSpanID

func WithSpanID(id uint64) StartSpanOption

WithSpanID sets the SpanID on the started span, instead of using a random number. If there is no parent Span (eg from ChildOf), then the TraceID will also be set to the value given here.

func WithSpanLinks(links []SpanLink) StartSpanOption

WithSpanLinks sets span links on the started span.

func WithStartSpanConfig

func WithStartSpanConfig(cfg *StartSpanConfig) StartSpanOption

WithStartSpanConfig merges the given StartSpanConfig into the one used to start the span. It is useful when you want to set a common base config, reducing the number of function calls in hot loops.

type TextMapCarrier

type TextMapCarrier map[string]string

TextMapCarrier allows the use of a regular map[string]string as both TextMapWriter and TextMapReader, making it compatible with the provided Propagator.

func (TextMapCarrier) ForeachKey

func (c TextMapCarrier) ForeachKey(handler func(key, val string) error) error

ForeachKey conforms to the TextMapReader interface.

func (TextMapCarrier) Set

func (c TextMapCarrier) Set(key, val string)

Set implements TextMapWriter.

type TextMapReader

type TextMapReader interface {
	// ForeachKey iterates over all keys that exist in the underlying
	// carrier. It takes a callback function which will be called
	// using all key/value pairs as arguments. ForeachKey will return
	// the first error returned by the handler.
	ForeachKey(handler func(key, val string) error) error
}

TextMapReader allows iterating over sets of key/value pairs. Carriers implementing TextMapReader are compatible to be used with Datadog's TextMapPropagator.

type TextMapWriter

type TextMapWriter interface {
	// Set sets the given key/value pair.
	Set(key, val string)
}

TextMapWriter allows setting key/value pairs of strings on the underlying data structure. Carriers implementing TextMapWriter are compatible to be used with Datadog's TextMapPropagator.

type Tracer

type Tracer interface {
	// StartSpan starts a span with the given operation name and options.
	StartSpan(operationName string, opts ...StartSpanOption) *Span

	// Extract extracts a span context from a given carrier. Note that baggage item
	// keys will always be lower-cased to maintain consistency. It is impossible to
	// maintain the original casing due to MIME header canonicalization standards.
	Extract(carrier interface{}) (*SpanContext, error)

	// Inject injects a span context into the given carrier.
	Inject(context *SpanContext, carrier interface{}) error

	// Stop stops the tracer. Calls to Stop should be idempotent.
	Stop()

	// TODO(kjn v2): These can be removed / consolidated. These are
	// here temporarily as we figure out a sensible API.
	TracerConf() TracerConf

	SubmitStats(*Span)
	SubmitAbandonedSpan(*Span, bool)
	SubmitChunk(any) // This is a horrible signature. This will eventually become SubmitChunk(Chunk)
	Flush()          // Synchronous flushing

}

Tracer specifies an implementation of the Datadog tracer which allows starting and propagating spans. The official implementation if exposed as functions within the "tracer" package.

func GetGlobalTracer

func GetGlobalTracer() Tracer

GetGlobalTracer returns the currently active tracer.

func NewUnstartedTracer

func NewUnstartedTracer(opts ...StartOption) (Tracer, error)

NewUnstartedTracer returns a new Tracer instance without starting it. This is

type TracerConf

type TracerConf struct {
	CanComputeStats      bool
	CanDropP0s           bool
	DebugAbandonedSpans  bool
	Disabled             bool
	PartialFlush         bool
	PartialFlushMinSpans int
	PeerServiceDefaults  bool
	PeerServiceMappings  map[string]string
	EnvTag               string
	VersionTag           string
	ServiceTag           string
}

type UserMonitoringConfig

type UserMonitoringConfig struct {
	PropagateID bool
	Email       string
	Name        string
	Role        string
	SessionID   string
	Scope       string
	Metadata    map[string]string
}

UserMonitoringConfig is used to configure what is used to identify a user. This configuration can be set by combining one or several UserMonitoringOption with a call to SetUser().

type UserMonitoringOption

type UserMonitoringOption func(*UserMonitoringConfig)

UserMonitoringOption represents a function that can be provided as a parameter to SetUser.

func WithPropagation

func WithPropagation() UserMonitoringOption

WithPropagation returns the option allowing the user id to be propagated through distributed traces. The user id is base64 encoded and added to the datadog propagated tags header. This option should only be used if you are certain that the user id passed to `SetUser()` does not contain any personal identifiable information or any kind of sensitive data, as it will be leaked to other services.

func WithUserEmail

func WithUserEmail(email string) UserMonitoringOption

WithUserEmail returns the option setting the email of the authenticated user.

func WithUserMetadata

func WithUserMetadata(key, value string) UserMonitoringOption

WithUserMetadata returns the option setting additional metadata of the authenticated user. This can be used multiple times and the given data will be tracked as `usr.{key}=value`.

func WithUserName

func WithUserName(name string) UserMonitoringOption

WithUserName returns the option setting the name of the authenticated user.

func WithUserRole

func WithUserRole(role string) UserMonitoringOption

WithUserRole returns the option setting the role of the authenticated user.

func WithUserScope

func WithUserScope(scope string) UserMonitoringOption

WithUserScope returns the option setting the scope (authorizations) of the authenticated user.

func WithUserSessionID

func WithUserSessionID(sessionID string) UserMonitoringOption

WithUserSessionID returns the option setting the session ID of the authenticated user.

Jump to

Keyboard shortcuts

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