ddtrace

package
v1.68.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2024 License: Apache-2.0, BSD-3-Clause, Apache-2.0 Imports: 4 Imported by: 865

Documentation

Overview

Package ddtrace contains the interfaces that specify the implementations of Datadog's tracing library, as well as a set of sub-packages containing various implementations: our native implementation ("tracer"), a wrapper that can be used with Opentracing ("opentracer") and a mock tracer to be used for testing ("mocktracer"). Additionally, package "ext" provides a set of tag names and values specific to Datadog's APM product.

To get started, visit the documentation for any of the packages you'd like to begin with by accessing the subdirectories of this package: https://godoc.org/gopkg.in/DataDog/dd-trace-go.v1/ddtrace#pkg-subdirectories.

Example (Datadog)

The below example illustrates a simple use case using the "tracer" package, our native Datadog APM tracing client integration. For thorough documentation and further examples, visit its own godoc page.

package main

import (
	"fmt"
	"log"
	"os"

	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace"
	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
)

func main() {
	// Start the tracer and defer the Stop method.
	tracer.Start(tracer.WithAgentAddr("host:port"))
	defer tracer.Stop()

	// Start a root span.
	span := tracer.StartSpan("get.data")
	defer span.Finish()

	// Create a child of it, computing the time needed to read a file.
	child := tracer.StartSpan("read.file", tracer.ChildOf(span.Context()))
	child.SetTag(ext.ResourceName, "test.json")

	// If you are using 128 bit trace ids and want to generate the high
	// order bits, cast the span's context to ddtrace.SpanContextW3C.
	// See Issue #1677
	if w3Cctx, ok := child.Context().(ddtrace.SpanContextW3C); ok {
		fmt.Printf("128 bit trace id = %s\n", w3Cctx.TraceID128())
	}

	// Perform an operation.
	_, err := os.ReadFile("~/test.json")

	// We may finish the child span using the returned error. If it's
	// nil, it will be disregarded.
	child.Finish(tracer.WithError(err))
	if err != nil {
		log.Fatal(err)
	}
}
Output:

Example (Mocking)

The code below illustrates a scenario of how one could use a mock tracer in tests to assert that spans are created correctly.

package main

import (
	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/mocktracer"
	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
)

func main() {
	// Setup the test environment: start the mock tracer.
	mt := mocktracer.Start()
	defer mt.Stop()

	// Run test code: in this example we will simply create a span to illustrate.
	tracer.StartSpan("test.span").Finish()

	// Assert the results: query the mock tracer for finished spans.
	spans := mt.FinishedSpans()
	if len(spans) != 1 {
		// fail
		panic("expected 1 span")
	}
	if spans[0].OperationName() != "test.span" {
		// fail
		panic("unexpected operation name")
	}
}
Output:

Example (Opentracing)

The below example illustrates how to set up an opentracing.Tracer using Datadog's tracer.

package main

import (
	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/opentracer"
	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"

	opentracing "github.com/opentracing/opentracing-go"
)

func main() {
	// Start a Datadog tracer, optionally providing a set of options,
	// returning an opentracing.Tracer which wraps it.
	t := opentracer.New(tracer.WithAgentAddr("host:port"))
	defer tracer.Stop() // important for data integrity (flushes any leftovers)

	// Use it with the Opentracing API. The (already started) Datadog tracer
	// may be used in parallel with the Opentracing API if desired.
	opentracing.SetGlobalTracer(t)
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func UseLogger added in v1.43.0

func UseLogger(l Logger)

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

Types

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.

type Logger added in v1.15.0

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.

type Span

type Span interface {
	// SetTag sets a key/value pair as metadata on the span.
	SetTag(key string, value interface{})

	// SetOperationName sets the operation name for this span. An operation name should be
	// a representative name for a group of spans (e.g. "grpc.server" or "http.request").
	SetOperationName(operationName string)

	// BaggageItem returns the baggage item held by the given key.
	BaggageItem(key string) string

	// SetBaggageItem sets a new baggage item at the given key. The baggage
	// item should propagate to all descendant spans, both in- and cross-process.
	SetBaggageItem(key, val string)

	// Finish finishes the current span with the given options. Finish calls should be idempotent.
	Finish(opts ...FinishOption)

	// Context returns the SpanContext of this Span.
	Context() SpanContext
}

Span represents a chunk of computation time. Spans have names, durations, timestamps and other metadata. A Tracer is used to create hierarchies of spans in a request, buffer and submit them to the server.

type SpanContext

type SpanContext interface {
	// SpanID returns the span ID that this context is carrying.
	SpanID() uint64

	// TraceID returns the trace ID that this context is carrying.
	TraceID() uint64

	// ForeachBaggageItem provides an iterator over the key/value pairs set as
	// baggage within this context. Iteration stops when the handler returns
	// false.
	ForeachBaggageItem(handler func(k, v string) bool)
}

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.

type SpanContextW3C added in v1.50.0

type SpanContextW3C interface {
	SpanContext

	// TraceID128 returns the hex-encoded 128-bit trace ID that this context is carrying.
	// The string will be exactly 32 bytes and may include leading zeroes.
	TraceID128() string

	// TraceID128 returns the raw bytes of the 128-bit trace ID that this context is carrying.
	TraceID128Bytes() [16]byte
}

SpanContextW3C represents a SpanContext with an additional method to allow access of the 128-bit trace id of the span, if present.

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

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

DecodeMsg implements msgp.Decodable

func (*SpanLink) EncodeMsg added in v1.61.0

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

EncodeMsg implements msgp.Encodable

func (*SpanLink) Msgsize added in v1.61.0

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

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

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.

type StartSpanOption

type StartSpanOption func(cfg *StartSpanConfig)

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

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()
}

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.

Directories

Path Synopsis
Package ext contains a set of Datadog-specific constants.
Package ext contains a set of Datadog-specific constants.
Package mocktracer provides a mock implementation of the tracer used in testing.
Package mocktracer provides a mock implementation of the tracer used in testing.
Package opentelemetry provides a wrapper on top of the Datadog tracer that can be used with OpenTelemetry.
Package opentelemetry provides a wrapper on top of the Datadog tracer that can be used with OpenTelemetry.
Package opentracer is in "Maintenance" mode and limited support is offered.
Package opentracer is in "Maintenance" mode and limited support is offered.
Package tracer contains Datadog's core tracing client.
Package tracer contains Datadog's core tracing client.

Jump to

Keyboard shortcuts

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