tracer

package
v1.62.0 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2024 License: Apache-2.0, BSD-3-Clause, Apache-2.0 Imports: 58 Imported by: 1,283

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/gopkg.in/DataDog/dd-trace-go.v1/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/gopkg.in/DataDog/dd-trace-go.v1/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/gopkg.in/DataDog/dd-trace-go.v1/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"

	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
	"gopkg.in/DataDog/dd-trace-go.v1/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 (
	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"
)

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 Extract

func Extract(carrier interface{}) (ddtrace.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 Flush added in v1.30.0

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 ddtrace.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 added in v1.54.0

func MarkIntegrationImported(integration string) bool

MarkIntegrationImported labels the given integration as imported

func SetDataStreamsCheckpoint added in v1.55.0

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 added in v1.55.0

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 SetUser added in v1.37.0

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)

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 TrackKafkaCommitOffset added in v1.55.0

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 added in v1.61.0

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 added in v1.55.0

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.

Types

type DBMPropagationMode added in v1.44.0

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 FinishOption

type FinishOption = ddtrace.FinishOption

FinishOption is a configuration option for FinishSpan. It is aliased in order to help godoc group all the functions returning it together. It is considered more correct to refer to it as the type as the origin, ddtrace.FinishOption.

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 added in v1.5.0

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 added in v1.14.0

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.

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 Propagator

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

	// Extract returns the SpanContext from the given carrier.
	Extract(carrier interface{}) (ddtrace.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 SQLCommentCarrier added in v1.39.0

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 added in v1.39.0

func (c *SQLCommentCarrier) Extract() (ddtrace.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 added in v1.39.0

func (c *SQLCommentCarrier) Inject(spanCtx ddtrace.SpanContext) error

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

type SQLCommentInjectionMode deprecated added in v1.39.0

type SQLCommentInjectionMode DBMPropagationMode

SQLCommentInjectionMode represents the mode of SQL comment injection.

Deprecated: Use DBMPropagationMode instead.

const (
	// SQLInjectionUndefined represents the comment injection mode is not set. This is the same as SQLInjectionDisabled.
	SQLInjectionUndefined SQLCommentInjectionMode = SQLCommentInjectionMode(DBMPropagationModeUndefined)
	// SQLInjectionDisabled represents the comment injection mode where all injection is disabled.
	SQLInjectionDisabled SQLCommentInjectionMode = SQLCommentInjectionMode(DBMPropagationModeDisabled)
	// SQLInjectionModeService represents the comment injection mode where only service tags (name, env, version) are injected.
	SQLInjectionModeService SQLCommentInjectionMode = SQLCommentInjectionMode(DBMPropagationModeService)
	// SQLInjectionModeFull represents the comment injection mode where both service tags and tracing tags. Tracing tags include span id, trace id and sampling priority.
	SQLInjectionModeFull SQLCommentInjectionMode = SQLCommentInjectionMode(DBMPropagationModeFull)
)

type Sampler

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

Sampler is the generic interface of any sampler. It must be safe for concurrent use.

type SamplingRule added in v1.24.0

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
	// 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 NameRule added in v1.24.0

func NameRule(name string, rate float64) SamplingRule

NameRule returns a SamplingRule that applies the provided sampling rate to spans that match the operation name provided.

func NameServiceRule added in v1.24.0

func NameServiceRule(name string, service string, rate float64) SamplingRule

NameServiceRule returns a SamplingRule that applies the provided sampling rate to spans matching both the operation and service names provided.

func RateRule added in v1.24.0

func RateRule(rate float64) SamplingRule

RateRule returns a SamplingRule that applies the provided sampling rate to all spans.

func ServiceRule added in v1.24.0

func ServiceRule(service string, rate float64) SamplingRule

ServiceRule returns a SamplingRule that applies the provided sampling rate to spans that match the service name provided.

func SpanNameServiceMPSRule added in v1.41.0

func SpanNameServiceMPSRule(name, service string, rate, limit float64) SamplingRule

SpanNameServiceMPSRule returns a SamplingRule of type SamplingRuleSpan that applies the provided sampling rate to all spans matching the operation and service name glob patterns up to the max number of spans per second that can be sampled. Operation and service fields must be valid glob patterns.

func SpanNameServiceRule added in v1.41.0

func SpanNameServiceRule(name, service string, rate float64) SamplingRule

SpanNameServiceRule returns a SamplingRule of type SamplingRuleSpan that applies the provided sampling rate to all spans matching the operation and service name glob patterns provided. Operation and service fields must be valid glob patterns.

func SpanTagsResourceRule added in v1.60.0

func SpanTagsResourceRule(tags map[string]string, resource, name, service string, rate float64) SamplingRule

SpanTagsResourceRule returns a SamplingRule that applies the provided sampling rate to spans that match resource, name, service and tags provided. Values of the tags map are expected to be in glob format.

func TagsResourceRule added in v1.60.0

func TagsResourceRule(tags map[string]*regexp.Regexp, resource, name, service string, rate float64) SamplingRule

TagsResourceRule returns a SamplingRule that applies the provided sampling rate to traces with spans that match resource, name, service and tags provided.

func (*SamplingRule) MarshalJSON added in v1.26.0

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

MarshalJSON implements the json.Marshaler interface.

func (*SamplingRule) UnmarshalJSON added in v1.62.0

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

type SamplingRuleType added in v1.41.0

type SamplingRuleType int

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

func (SamplingRuleType) String added in v1.41.0

func (sr SamplingRuleType) String() string

type Span

type Span = ddtrace.Span

Span is an alias for ddtrace.Span. It is here to allow godoc to group methods returning ddtrace.Span. It is recommended and is considered more correct to refer to this type as ddtrace.Span instead.

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 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`.

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 WithAnalytics added in v1.11.0

func WithAnalytics(on bool) StartOption

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

func WithAnalyticsRate added in v1.11.0

func WithAnalyticsRate(rate float64) StartOption

WithAnalyticsRate sets the global sampling rate for sampling APM events.

func WithContribStats added in v1.62.0

func WithContribStats(enabled bool) StartOption

WithContribStats opens up a channel of communication between tracer and contrib libraries for submitting stats from contribs to Datadog via the tracer's statsd client It is enabled by default but can be disabled with `WithContribStats(false)`

func WithDebugMode

func WithDebugMode(enabled bool) StartOption

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

func WithDebugSpansMode added in v1.55.0

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 added in v1.27.0

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 added in v1.18.0

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 added in v1.20.0

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 added in v1.31.1

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 added in v1.52.0

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 added in v1.24.0

func WithHTTPClient(client *http.Client) StartOption

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

func WithHTTPRoundTripper added in v1.7.0

func WithHTTPRoundTripper(r http.RoundTripper) StartOption

WithHTTPRoundTripper is deprecated. Please consider using WithHTTPClient instead. The function allows customizing the underlying HTTP transport for emitting spans.

func WithHeaderTags added in v1.53.0

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 added in v1.29.0

func WithHostname(name string) StartOption

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

func WithLambdaMode added in v1.27.0

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 added in v1.34.0

func WithLogStartup(enabled bool) StartOption

WithLogStartup allows enabling or disabling the startup log.

func WithLogger added in v1.15.0

func WithLogger(logger ddtrace.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 added in v1.55.0

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 added in v1.54.0

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 added in v1.52.0

func WithPeerServiceDefaults(enabled bool) StartOption

WithPeerServiceDefaults sets default calculation for peer.service.

func WithPeerServiceMapping added in v1.52.0

func WithPeerServiceMapping(from, to string) StartOption

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

func WithPrioritySampling added in v1.7.0

func WithPrioritySampling() StartOption

WithPrioritySampling is deprecated, and priority sampling is enabled by default. When using distributed tracing, the priority sampling value is propagated in order to get all the parts of a distributed trace sampled. To learn more about priority sampling, please visit: https://docs.datadoghq.com/tracing/getting_further/trace_sampling_and_storage/#priority-sampling-for-distributed-tracing

func WithProfilerCodeHotspots added in v1.35.0

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 added in v1.35.0

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 added in v1.18.0

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.

func WithSamplingRules added in v1.24.0

func WithSamplingRules(rules []SamplingRule) StartOption

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

func WithSendRetries added in v1.48.0

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 added in v1.24.0

func WithService(name string) StartOption

WithService sets the default service name for the program.

func WithServiceMapping added in v1.35.0

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 WithServiceName

func WithServiceName(name string) StartOption

WithServiceName is deprecated. Please use WithService. If you are using an older version and you are upgrading from WithServiceName to WithService, please note that WithService will determine the service name of server and framework integrations.

func WithServiceVersion added in v1.24.0

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 added in v1.55.0

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 WithTraceEnabled added in v1.35.0

func WithTraceEnabled(enabled bool) StartOption

WithTraceEnabled allows specifying whether tracing will be enabled

func WithUDS added in v1.29.0

func WithUDS(socketPath string) StartOption

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

func WithUniversalVersion added in v1.39.0

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 StartSpanOption

type StartSpanOption = ddtrace.StartSpanOption

StartSpanOption is a configuration option for StartSpan. It is aliased in order to help godoc group all the functions returning it together. It is considered more correct to refer to it as the type as the origin, ddtrace.StartSpanOption.

func AnalyticsRate added in v1.24.0

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

func ChildOf(ctx ddtrace.SpanContext) StartSpanOption

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

func Measured added in v1.24.0

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 added in v1.10.0

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 []ddtrace.SpanLink) StartSpanOption

WithSpanLinks sets span links on the started span.

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 UserMonitoringConfig added in v1.41.0

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 added in v1.37.0

type UserMonitoringOption func(*UserMonitoringConfig)

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

func WithPropagation added in v1.41.0

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 added in v1.37.0

func WithUserEmail(email string) UserMonitoringOption

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

func WithUserMetadata added in v1.53.0

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 added in v1.37.0

func WithUserName(name string) UserMonitoringOption

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

func WithUserRole added in v1.37.0

func WithUserRole(role string) UserMonitoringOption

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

func WithUserScope added in v1.37.0

func WithUserScope(scope string) UserMonitoringOption

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

func WithUserSessionID added in v1.37.0

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