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 ¶
- Constants
- Variables
- func ContextWithSpan(ctx context.Context, span *Span) context.Context
- func Disable()
- func Enable()
- type Encoder
- type Span
- func NewChildSpan(name string, parent *Span) *Span
- func NewChildSpanFromContext(name string, ctx context.Context) *Span
- func NewRootSpan(name, service, resource string) *Span
- func NewSpan(name, service, resource string, spanID, traceID, parentID uint64, ...) *Span
- func SpanFromContext(ctx context.Context) (*Span, bool)
- func SpanFromContextDefault(ctx context.Context) *Span
- func (s *Span) Context(ctx context.Context) context.Context
- func (s *Span) Finish()
- func (s *Span) FinishWithErr(err error)
- func (s *Span) GetMeta(key string) string
- func (s *Span) SetError(err error)
- func (s *Span) SetMeta(key, value string)
- func (s *Span) SetMetric(key string, val float64)
- func (s *Span) SetMetrics(key string, value float64)
- func (s *Span) String() string
- func (s *Span) Tracer() *Tracer
- type Tracer
- func (t *Tracer) Enabled() bool
- func (t *Tracer) Flush() error
- func (t *Tracer) NewChildSpan(name string, parent *Span) *Span
- func (t *Tracer) NewChildSpanFromContext(name string, ctx context.Context) *Span
- func (t *Tracer) NewRootSpan(name, service, resource string) *Span
- func (t *Tracer) SetEnabled(enabled bool)
- func (t *Tracer) SetSampleRate(sampleRate float64)
- type Transport
Examples ¶
Constants ¶
const ( JSON_ENCODER = iota MSGPACK_ENCODER )
Variables ¶
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 ¶
ContextWithSpan will return a new context that includes the given span. DEPRECATED: use span.Context(ctx) instead.
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 ¶
NewChildSpan creates a span that is a child of parent. It will inherit the parent's service and resource.
func NewChildSpanFromContext ¶
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 ¶
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 ¶
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 ¶
SpanFromContextDefault returns the stored *Span from the Context. If not, it will return an empty span that will do nothing.
func (*Span) 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 ¶
FinishWithErr marks a span finished and sets the given error if it's non-nil.
func (*Span) GetMeta ¶
GetMeta will return the value for the given tag or the empty string if it doesn't exist.
func (*Span) SetError ¶
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) SetMetrics ¶
SetMetrics adds a metric field to the current Span. DEPRECATED: Use SetMetric
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 ¶
NewTracerTransport create a new Tracer with the given transport.
func (*Tracer) NewChildSpan ¶
NewChildSpan returns a new span that is child of the Span passed as argument.
func (*Tracer) NewChildSpanFromContext ¶
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 ¶
NewRootSpan creates a span with no parent. Its ids will be randomly assigned.
func (*Tracer) SetEnabled ¶
SetEnabled will enable or disable the tracer.
func (*Tracer) SetSampleRate ¶
SetSampleRate sets a sample rate for all the future traces. sampleRate has to be between 0 (sample nothing) and 1 (sample everything).
Source Files ¶
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. |