tracer

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2016 License: BSD-3-Clause Imports: 12 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.

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

Types

type Encoder

type Encoder interface {
	Encode(traces [][]*Span) error
	Read(p []byte) (int, error)
	ContentType() string
}

Encoder is a generic interface that expects an Encode() method for the encoding process, and a Read() method that will be used by the http handler

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 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) Flush

func (t *Tracer) Flush() error

Flush will push any currently buffered traces to the server.

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) SetSampleRate

func (t *Tracer) SetSampleRate(sampleRate float64)

SetSampleRate sets a sample rate for all the future traces. sampleRate has to be between 0 (sample nothing) and 1 (sample everything).

type Transport

type Transport interface {
	Send(spans [][]*Span) (*http.Response, error)
	SetHeader(key, value string)
}

Transport is an interface for span submission to the agent.

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.
gorilla/muxtrace
Package muxtrace provides tracing functions for the Gorilla Mux framework.
Package muxtrace provides tracing functions for the Gorilla Mux framework.

Jump to

Keyboard shortcuts

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