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.
To enable APM and/or tracing of supported integrations, follow the instructions for the appropriate package: https://godoc.org/github.com/DataDog/dd-trace-go/tracer#pkg-subdirectories
Sample code is available in the two examples below:
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, and // attach it to the current context. If the context has no span, it will // return an empty root span. span, ctx := tracer.NewChildSpanWithContext("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 ¶
- Variables
- func ContextWithSpan(ctx context.Context, span *Span) context.Context
- func Disable()
- func Enable()
- func NextSpanID() uint64
- type Encoder
- type Service
- type Span
- func NewChildSpan(name string, parent *Span) *Span
- func NewChildSpanFromContext(name string, ctx context.Context) *Span
- func NewChildSpanWithContext(name string, ctx context.Context) (*Span, context.Context)
- 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) FinishWithTime(finishTime int64)
- func (s *Span) GetMeta(key string) string
- func (s *Span) GetSamplingPriority() int
- func (s *Span) HasSamplingPriority() bool
- func (s *Span) SetError(err error)
- func (s *Span) SetMeta(key, value string)
- func (s *Span) SetMetas(metas map[string]string)
- func (s *Span) SetMetric(key string, val float64)
- func (s *Span) SetMetrics(key string, value float64)
- func (s *Span) SetSamplingPriority(priority int)
- func (s *Span) String() string
- func (s *Span) Tracer() *Tracer
- type Tracer
- func (t *Tracer) DebugLoggingEnabled() bool
- func (t *Tracer) Enabled() bool
- func (t *Tracer) ForceFlush()
- func (t *Tracer) NewChildSpan(name string, parent *Span) *Span
- func (t *Tracer) NewChildSpanFromContext(name string, ctx context.Context) *Span
- func (t *Tracer) NewChildSpanWithContext(name string, ctx context.Context) (*Span, context.Context)
- func (t *Tracer) NewRootSpan(name, service, resource string) *Span
- func (t *Tracer) Sample(span *Span)
- func (t *Tracer) SetDebugLogging(debug bool)
- func (t *Tracer) SetEnabled(enabled bool)
- func (t *Tracer) SetMeta(key, value string)
- func (t *Tracer) SetSampleRate(sampleRate float64)
- func (t *Tracer) SetServiceInfo(name, app, appType string)
- func (t *Tracer) Stop()
- type Transport
Examples ¶
Constants ¶
This section is empty.
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 { 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 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 sync.RWMutex // 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 NewChildSpanWithContext ¶ added in v0.5.0
NewChildSpanWithContext will create and return a child span of the span contained in the given context, as well as a copy of the parent context containing the created child span. If the context contains no span, an empty root span will be returned. If nil is passed in for the context, a context will be created.
func NewRootSpan ¶
NewRootSpan creates a span with no parent. Its 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. This is a low-level function, required for testing and advanced usage. Most of the time one should prefer the Tracer NewRootSpan or NewChildSpan methods.
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. Once a Span has been finished, methods that modify the Span will become no-ops.
func (*Span) FinishWithErr ¶
FinishWithErr marks a span finished and sets the given error if it's non-nil.
func (*Span) FinishWithTime ¶ added in v0.6.0
FinishWithTime closes this Span at the given `finishTime`. The behavior is the same as `Finish()`.
func (*Span) GetMeta ¶
GetMeta will return the value for the given tag or the empty string if it doesn't exist.
func (*Span) GetSamplingPriority ¶ added in v0.6.0
GetSamplingPriority gets the sampling priority.
func (*Span) HasSamplingPriority ¶ added in v0.6.0
HasSamplingPriority returns true if sampling priority is set. It can be defined to either zero or non-zero.
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. If the Span has been finished, it will not be modified by this method.
func (*Span) SetMeta ¶
SetMeta adds an arbitrary meta field to the current Span. If the Span has been finished, it will not be modified by the method.
func (*Span) SetMetas ¶ added in v0.5.0
SetMetas adds arbitrary meta fields from a given map to the current Span. If the Span has been finished, it will not be modified by the method.
func (*Span) SetMetric ¶
SetMetric sets a float64 value for the given key. It acts like `set_meta()` and it simply add a tag without further processing. This method doesn't create a Datadog metric.
func (*Span) SetMetrics ¶
SetMetrics adds a metric field to the current Span. DEPRECATED: Use SetMetric
func (*Span) SetSamplingPriority ¶ added in v0.6.0
SetSamplingPriority sets the sampling priority.
type Tracer ¶
type Tracer struct {
// 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) DebugLoggingEnabled ¶
DebugLoggingEnabled returns true if the debug level is enabled and false otherwise.
func (*Tracer) ForceFlush ¶ added in v0.5.0
func (t *Tracer) ForceFlush()
ForceFlush forces a flush of data (traces and services) to the agent. Flushes are done by a background task on a regular basis, so you never need to call this manually, mostly useful for testing and debugging.
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) NewChildSpanWithContext ¶ added in v0.5.0
NewChildSpanWithContext will create and return a child span of the span contained in the given context, as well as a copy of the parent context containing the created child span. If the context contains no span, an empty root span will be returned. If nil is passed in for the context, a context will be created.
func (*Tracer) NewRootSpan ¶
NewRootSpan creates a span with no parent. Its ids will be randomly assigned.
func (*Tracer) SetDebugLogging ¶ added in v0.5.1
SetDebugLogging will set the debug level
func (*Tracer) SetEnabled ¶
SetEnabled will enable or disable the tracer.
func (*Tracer) SetMeta ¶ added in v0.4.0
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 ¶
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
SetServiceInfo update the application and application type for the given service.
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
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.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
contrib
|
|
elastictraced
Package elastictraced provides tracing for the Elastic Elasticsearch client.
|
Package elastictraced provides tracing for the Elastic Elasticsearch client. |
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) |
gocql
Package gocqltrace provides tracing for the Cassandra Gocql client (https://github.com/gocql/gocql)
|
Package gocqltrace provides tracing for the Cassandra Gocql client (https://github.com/gocql/gocql) |
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/sqltest
Package sqltest is used for testing sql packages
|
Package sqltest is used for testing sql packages |
sqltraced/sqlutils
Package sqlutils share some utils functions for sql packages
|
Package sqlutils share some utils functions for sql packages |
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. |