tracer

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: May 9, 2017 License: BSD-3-Clause Imports: 21 Imported by: 0

Documentation

Overview

Package tracer contains Datadog's tracing client. It is used to trace requests as they flow across web servers, databases and microservices so that developers have visibility into bottlenecks and troublesome requests.

Package tracer has two core objects: Tracers and Spans. Spans represent a chunk of computation time. They have names, durations, timestamps and other metadata. Tracers are used to create hierarchies of spans in a request, buffer and submit them to the server.

The tracing client can perform trace sampling. While the trace agent already samples traces to reduce bandwidth usage, client sampling reduces performance overhead.

Example
package main

import (
	"net/http"

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

func main() {
	span := tracer.NewRootSpan("http.client.request", "example.com", "/user/{id}")
	defer span.Finish()

	url := "http://example.com/user/123"

	resp, err := http.Get(url)
	if err != nil {
		span.SetError(err)
		return
	}

	span.SetMeta("http.status", resp.Status)
	span.SetMeta("http.url", url)
}
Output:

Example (Context)

Tracing the hierarchy of spans in a request is a key part of tracing. This, for example, let's a developer associate all of the database calls in a web request. As of Go 1.7, the standard way of doing this is with the context package. Along with supporting deadlines, cancellation signals and more, Contexts are perfect for passing (optional) telemetry data through your stack.

Read more about contexts here: https://golang.org/pkg/context/

Here is an example illustrating how to pass tracing data with contexts.

package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"

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

func saveFile(ctx context.Context, path string, r io.Reader) error {
	// Start a new span that is the child of the span stored in the context. If the span
	// has no context, it will return an empty one.
	span := tracer.NewChildSpanFromContext("filestore.saveFile", ctx)
	defer span.Finish()

	// save the file contents.
	file, err := os.Create(path)
	if err != nil {
		span.SetError(err)
		return err
	}
	defer file.Close()

	_, err = io.Copy(file, r)
	span.SetError(err)
	return err
}

func saveFileHandler(w http.ResponseWriter, r *http.Request) {
	// the name of the operation we're measuring
	name := "http.request"
	service := "example-filestore"
	resource := "/saveFile"

	// This is the main entry point of our application, so we create a root span
	// that includes the service and resource name.
	span := tracer.NewRootSpan(name, service, resource)
	defer span.Finish()

	// Add the span to the request's context so we can pass the tracing information
	// down the stack.
	ctx := span.Context(r.Context())

	// Do the work.
	err := saveFile(ctx, "/tmp/example", r.Body)
	span.SetError(err) // no-op if err == nil

	if err != nil {
		http.Error(w, fmt.Sprintf("error saving file! %s", err), 500)
		return
	}

	w.Write([]byte("saved file!"))
}

// Tracing the hierarchy of spans in a request is a key part of tracing. This, for example,
// let's a developer associate all of the database calls in a web request. As of Go 1.7,
// the standard way of doing this is with the context package. Along with supporting
// deadlines, cancellation signals and more, Contexts are perfect for passing (optional)
// telemetry data through your stack.
//
// Read more about contexts here: https://golang.org/pkg/context/
//
// Here is an example illustrating how to pass tracing data with contexts.
func main() {
	http.HandleFunc("/saveFile", saveFileHandler)
	log.Fatal(http.ListenAndServe(":8080", nil))
}
Output:

Index

Examples

Constants

View Source
const (
	JSON_ENCODER = iota
	MSGPACK_ENCODER
)

Variables

View Source
var DefaultTracer = NewTracer()

DefaultTracer is a global tracer that is enabled by default. All of the packages top level NewSpan functions use the default tracer.

span := tracer.NewRootSpan("sql.query", "user-db", "select * from foo where id = ?")
defer span.Finish()

Functions

func CompareSpan added in v0.4.0

func CompareSpan(t *testing.T, expectedSpan, actualSpan *Span, debug ...bool)

Test strict equality between the most important fields of the two spans

func ContextWithSpan

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

ContextWithSpan will return a new context that includes the given span. DEPRECATED: use span.Context(ctx) instead.

func Disable

func Disable()

Disable will disable the default tracer.

func Enable

func Enable()

Enable will enable the default tracer.

func GetTestTracer added in v0.4.0

func GetTestTracer() (*Tracer, *DummyTransport)

Return a Tracer with a DummyTransport

func NextSpanID added in v0.4.0

func NextSpanID() uint64

NextSpanID returns a new random span id.

Types

type DummyTransport added in v0.4.0

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

dummyTransport is a transport that just buffers spans and encoding

func (*DummyTransport) SendServices added in v0.4.0

func (t *DummyTransport) SendServices(services map[string]Service) (*http.Response, error)

func (*DummyTransport) SendTraces added in v0.4.0

func (t *DummyTransport) SendTraces(traces [][]*Span) (*http.Response, error)

func (*DummyTransport) SetHeader added in v0.4.0

func (t *DummyTransport) SetHeader(key, value string)

func (*DummyTransport) Traces added in v0.4.0

func (t *DummyTransport) Traces() [][]*Span

type Encoder

type Encoder interface {
	EncodeTraces(traces [][]*Span) error
	EncodeServices(services map[string]Service) error
	Read(p []byte) (int, error)
	ContentType() string
}

Encoder is a generic interface that expects encoding methods for traces and services, and a Read() method that will be used by the http handler

type Service added in v0.2.0

type Service struct {
	Name    string `json:"-"`        // the internal of the service (e.g. acme_search, datadog_web)
	App     string `json:"app"`      // the name of the application (e.g. rails, postgres, custom-app)
	AppType string `json:"app_type"` // the type of the application (e.g. db, web)
}

func (Service) Equal added in v0.2.0

func (s Service) Equal(s2 Service) bool

type Span

type Span struct {
	// Name is the name of the operation being measured. Some examples
	// might be "http.handler", "fileserver.upload" or "video.decompress".
	// Name should be set on every span.
	Name string `json:"name"`

	// Service is the name of the process doing a particular job. Some
	// examples might be "user-database" or "datadog-web-app". Services
	// will be inherited from parents, so only set this in your app's
	// top level span.
	Service string `json:"service"`

	// Resource is a query to a service. A web application might use
	// resources like "/user/{user_id}". A sql database might use resources
	// like "select * from user where id = ?".
	//
	// You can track thousands of resources (not millions or billions) so
	// prefer normalized resources like "/user/{id}" to "/user/123".
	//
	// Resources should only be set on an app's top level spans.
	Resource string `json:"resource"`

	Type     string             `json:"type"`              // protocol associated with the span
	Start    int64              `json:"start"`             // span start time expressed in nanoseconds since epoch
	Duration int64              `json:"duration"`          // duration of the span expressed in nanoseconds
	Meta     map[string]string  `json:"meta,omitempty"`    // arbitrary map of metadata
	Metrics  map[string]float64 `json:"metrics,omitempty"` // arbitrary map of numeric metrics
	SpanID   uint64             `json:"span_id"`           // identifier of this span
	TraceID  uint64             `json:"trace_id"`          // identifier of the root span
	ParentID uint64             `json:"parent_id"`         // identifier of the span's direct parent
	Error    int32              `json:"error"`             // error status of the span; 0 means no errors
	Sampled  bool               `json:"-"`                 // if this span is sampled (and should be kept/recorded) or not
	// contains filtered or unexported fields
}

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

span := tracer.NewRootSpan("web.request", "datadog.com", "/user/{id}")
defer span.Finish()  // or FinishWithErr(err)

In general, spans should be created with the tracer.NewSpan* functions, so they will be submitted on completion.

func CopySpan added in v0.4.0

func CopySpan(span *Span, trc *Tracer) *Span

CopySpan returns a new span with the same fields of the copied one. This function is necessary because the usual assignment copies the mutex address and then the use of the copied span can conflict with the original one when concurent calls.

func NewChildSpan

func NewChildSpan(name string, parent *Span) *Span

NewChildSpan creates a span that is a child of parent. It will inherit the parent's service and resource.

func NewChildSpanFromContext

func NewChildSpanFromContext(name string, ctx context.Context) *Span

NewChildSpanFromContext will create a child span of the span contained in the given context. If the context contains no span, a span with no service or resource will be returned.

func NewRootSpan

func NewRootSpan(name, service, resource string) *Span

NewRootSpan creates a span with no parent. It's ids will be randomly assigned.

func NewSpan

func NewSpan(name, service, resource string, spanID, traceID, parentID uint64, tracer *Tracer) *Span

NewSpan creates a new span.

func SpanFromContext

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

SpanFromContext returns the stored *Span from the Context if it's available. This helper returns also the ok value that is true if the span is present.

func SpanFromContextDefault

func SpanFromContextDefault(ctx context.Context) *Span

SpanFromContextDefault returns the stored *Span from the Context. If not, it will return an empty span that will do nothing.

func (*Span) Context

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

Context returns a copy of the given context that includes this span. This span can be accessed downstream with SpanFromContext and friends.

func (*Span) Finish

func (s *Span) Finish()

Finish closes this Span (but not its children) providing the duration of this part of the tracing session. This method is idempotent so calling this method multiple times is safe and doesn't update the current Span.

func (*Span) FinishWithErr

func (s *Span) FinishWithErr(err error)

FinishWithErr marks a span finished and sets the given error if it's non-nil.

func (*Span) GetMeta

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

GetMeta will return the value for the given tag or the empty string if it doesn't exist.

func (*Span) SetError

func (s *Span) SetError(err error)

SetError stores an error object within the span meta. The Error status is updated and the error.Error() string is included with a default meta key.

func (*Span) SetMeta

func (s *Span) SetMeta(key, value string)

SetMeta adds an arbitrary meta field to the current Span.

func (*Span) SetMetric

func (s *Span) SetMetric(key string, val float64)

SetMetric adds a metric field to the current Span.

func (*Span) SetMetrics

func (s *Span) SetMetrics(key string, value float64)

SetMetrics adds a metric field to the current Span. DEPRECATED: Use SetMetric

func (*Span) String

func (s *Span) String() string

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

func (*Span) Tracer

func (s *Span) Tracer() *Tracer

Tracer returns the tracer that created this span.

type Tracer

type Tracer struct {
	DebugLoggingEnabled bool
	// contains filtered or unexported fields
}

Tracer creates, buffers and submits Spans which are used to time blocks of compuration.

When a tracer is disabled, it will not submit spans for processing.

func NewTracer

func NewTracer() *Tracer

NewTracer creates a new Tracer. Most users should use the package's DefaultTracer instance.

func NewTracerTransport

func NewTracerTransport(transport Transport) *Tracer

NewTracerTransport create a new Tracer with the given transport.

func (*Tracer) Enabled

func (t *Tracer) Enabled() bool

Enabled returns whether or not a tracer is enabled.

func (*Tracer) FlushTraces added in v0.2.0

func (t *Tracer) FlushTraces() error

FlushTraces will push any currently buffered traces to the server. XXX Note that it is currently exported because some tests use it. They really should not.

func (*Tracer) NewChildSpan

func (t *Tracer) NewChildSpan(name string, parent *Span) *Span

NewChildSpan returns a new span that is child of the Span passed as argument.

func (*Tracer) NewChildSpanFromContext

func (t *Tracer) NewChildSpanFromContext(name string, ctx context.Context) *Span

NewChildSpanFromContext will create a child span of the span contained in the given context. If the context contains no span, an empty span will be returned.

func (*Tracer) NewRootSpan

func (t *Tracer) NewRootSpan(name, service, resource string) *Span

NewRootSpan creates a span with no parent. Its ids will be randomly assigned.

func (*Tracer) SetEnabled

func (t *Tracer) SetEnabled(enabled bool)

SetEnabled will enable or disable the tracer.

func (*Tracer) SetMeta added in v0.4.0

func (t *Tracer) SetMeta(key, value string)

SetMeta adds an arbitrary meta field at the tracer level. This will append those tags to each span created by the tracer.

func (*Tracer) SetSampleRate

func (t *Tracer) SetSampleRate(sampleRate float64)

SetSampleRate sets a sample rate for all the future traces. sampleRate has to be between 0.0 and 1.0 and represents the ratio of traces that will be sampled. 0.0 means that the tracer won't send any trace. 1.0 means that the tracer will send all traces.

func (*Tracer) SetServiceInfo added in v0.2.0

func (t *Tracer) SetServiceInfo(name, app, appType string)

SetServiceInfo update the application and application type for the given service.

func (*Tracer) SetSpansBufferSize added in v0.3.0

func (t *Tracer) SetSpansBufferSize(maxSize int)

SetSpansBufferSize sets a buffer size for the tracer. This abandons the old buffer so this should be called in an init function otherwise already recorded spans will be lost. maxSize must be greater than 0

func (*Tracer) Stop added in v0.2.0

func (t *Tracer) Stop()

Stop stops the tracer.

type Transport

type Transport interface {
	SendTraces(spans [][]*Span) (*http.Response, error)
	SendServices(services map[string]Service) (*http.Response, error)
	SetHeader(key, value string)
}

Transport is an interface for span submission to the agent.

func NewTransport added in v0.2.0

func NewTransport(hostname, port string) Transport

NewTransport returns a new Transport implementation that sends traces to a trace agent running on the given hostname and port. If the zero values for hostname and port are provided, the default values will be used ("localhost" for hostname, and "8126" for port).

In general, using this method is only necessary if you have a trace agent running on a non-default port or if it's located on another machine.

Directories

Path Synopsis
contrib
gin-gonic/gintrace
Package gintrace provides tracing middleware for the Gin web framework.
Package gintrace provides tracing middleware for the Gin web framework.
go-redis
Package goredistrace provides tracing for the go-redis Redis client (https://github.com/go-redis/redis)
Package goredistrace provides tracing for the go-redis Redis client (https://github.com/go-redis/redis)
gorilla/muxtrace
Package muxtrace provides tracing functions for the Gorilla Mux framework.
Package muxtrace provides tracing functions for the Gorilla Mux framework.
redigo
Package redigotrace provides tracing for the Redigo Redis client (https://github.com/garyburd/redigo)
Package redigotrace provides tracing for the Redigo Redis client (https://github.com/garyburd/redigo)
sqltraced
Package sqltraced provides a traced version of any driver implementing the database/sql/driver interface.
Package sqltraced provides a traced version of any driver implementing the database/sql/driver interface.
sqltraced/parsedsn
Package parsedsn provides functions to parse any kind of DSNs into a map[string]string
Package parsedsn provides functions to parse any kind of DSNs into a map[string]string
sqltraced/parsedsn/mysql
Package mysql is the minimal fork of go-sql-driver/mysql so we can use their code to parse the mysql DSNs
Package mysql is the minimal fork of go-sql-driver/mysql so we can use their code to parse the mysql DSNs
sqltraced/parsedsn/pq
Package pq is the minimal fork of lib/pq so we can use their code to parse the postgres DSNs
Package pq is the minimal fork of lib/pq so we can use their code to parse the postgres DSNs
sqltraced/sqlutils
Package sqlutils share some utils functions for sql testing
Package sqlutils share some utils functions for sql testing
sqlxtraced
Package sqlxtraced provides a traced version of the "jmoiron/sqlx" package For more information about the API, see https://godoc.org/github.com/DataDog/dd-trace-go/tracer/contrib/sqltraced.
Package sqlxtraced provides a traced version of the "jmoiron/sqlx" package For more information about the API, see https://godoc.org/github.com/DataDog/dd-trace-go/tracer/contrib/sqltraced.

Jump to

Keyboard shortcuts

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