elasticapm

package module
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2018 License: Apache-2.0 Imports: 36 Imported by: 0

README

GoDoc Travis-CI AppVeyor Go Report Card codecov.io

apm-agent-go: APM Agent for Go (beta)

This is the official Go package for Elastic APM.

The Go agent enables you to trace the execution of operations in your application, sending performance metrics and errors to the Elastic APM server.

We'd love to hear your feedback, please take a minute to fill out our survey.

Installation

go get -u github.com/elastic/apm-agent-go

Requirements

Tested with Go 1.8+ on Linux, Windows and MacOS.

License

Apache 2.0.

Documentation

Elastic APM Go documentation.

Getting Help

If you find a bug, please report an issue. For any other assistance, please open or add to a topic on the APM discuss forum.

Documentation

Overview

Package elasticapm provides an API for tracing transactions and capturing errors, sending the data to Elastic APM.

Index

Examples

Constants

View Source
const (
	// AgentVersion is the Elastic APM Go Agent version.
	AgentVersion = "0.5.2"
)

Variables

This section is empty.

Functions

func ContextWithSpan

func ContextWithSpan(parent context.Context, s *Span) context.Context

ContextWithSpan returns a copy of parent in which the given span is stored, associated with the key ContextSpanKey.

func ContextWithTransaction

func ContextWithTransaction(parent context.Context, t *Transaction) context.Context

ContextWithTransaction returns a copy of parent in which the given transaction is stored, associated with the key ContextTransactionKey.

Types

type BodyCapturer

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

BodyCapturer is returned by Tracer.CaptureHTTPRequestBody to later be passed to Context.SetHTTPRequestBody.

type CaptureBodyMode

type CaptureBodyMode int

CaptureBodyMode holds a value indicating how a tracer should capture HTTP request bodies: for transactions, for errors, for both, or neither.

const (
	// CaptureBodyOff disables capturing of HTTP request bodies. This is
	// the default mode.
	CaptureBodyOff CaptureBodyMode = 0

	// CaptureBodyErrors captures HTTP request bodies for only errors.
	CaptureBodyErrors CaptureBodyMode = 1

	// CaptureBodyTransactions captures HTTP request bodies for only
	// transactions.
	CaptureBodyTransactions CaptureBodyMode = 1 << 1

	// CaptureBodyAll captures HTTP request bodies for both transactions
	// and errors.
	CaptureBodyAll CaptureBodyMode = CaptureBodyErrors | CaptureBodyTransactions
)

type Context

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

Context provides methods for setting transaction and error context.

func (*Context) SetCustom

func (c *Context) SetCustom(key string, value interface{})

SetCustom sets a custom context key/value pair. If the key is invalid (contains '.', '*', or '"'), the call is a no-op. The value must be JSON-encodable.

If value implements interface{AppendJSON([]byte) []byte}, that will be used to encode the value. Otherwise, value will be encoded using json.Marshal. As a special case, values of type map[string]interface{} will be traversed and values encoded according to the same rules.

func (*Context) SetHTTPRequest

func (c *Context) SetHTTPRequest(req *http.Request)

SetHTTPRequest sets details of the HTTP request in the context.

This function relates to server-side requests. Various proxy forwarding headers are taken into account to reconstruct the URL, and determining the client address.

If the request URL contains user info, it will be removed and excluded from the URL's "full" field.

If the request contains HTTP Basic Authentication, the username from that will be recorded in the context. Otherwise, if the request contains user info in the URL (i.e. a client-side URL), that will be used.

func (*Context) SetHTTPRequestBody

func (c *Context) SetHTTPRequestBody(bc *BodyCapturer)

SetHTTPRequestBody sets the request body in context given a (possibly nil) BodyCapturer returned by Tracer.CaptureHTTPRequestBody.

func (*Context) SetHTTPResponseFinished

func (c *Context) SetHTTPResponseFinished(finished bool)

SetHTTPResponseFinished records whether or not the response was finished.

func (*Context) SetHTTPResponseHeaders

func (c *Context) SetHTTPResponseHeaders(h http.Header)

SetHTTPResponseHeaders sets the HTTP response headers in the context.

func (*Context) SetHTTPResponseHeadersSent

func (c *Context) SetHTTPResponseHeadersSent(headersSent bool)

SetHTTPResponseHeadersSent records whether or not response were sent.

func (*Context) SetHTTPStatusCode

func (c *Context) SetHTTPStatusCode(statusCode int)

SetHTTPStatusCode records the HTTP response status code.

func (*Context) SetTag

func (c *Context) SetTag(key, value string)

SetTag sets a tag in the context. If the key is invalid (contains '.', '*', or '"'), the call is a no-op.

func (*Context) SetUserEmail added in v0.5.0

func (c *Context) SetUserEmail(email string)

SetUserEmail sets the email for the authenticated user.

func (*Context) SetUserID added in v0.5.0

func (c *Context) SetUserID(id string)

SetUserID sets the ID of the authenticated user.

func (*Context) SetUsername added in v0.5.0

func (c *Context) SetUsername(username string)

SetUsername sets the username of the authenticated user.

type DatabaseSpanContext

type DatabaseSpanContext struct {
	// Instance holds the database instance name.
	Instance string

	// Statement holds the statement executed in the span,
	// e.g. "SELECT * FROM foo".
	Statement string

	// Type holds the database type, e.g. "sql".
	Type string

	// User holds the username used for database access.
	User string
}

DatabaseSpanContext holds database span context.

type Error

type Error struct {

	// ID is the unique ID of the error. This is set by NewError,
	// and can be used for correlating errors and log records.
	ID ErrorID

	// Culprit is the name of the function that caused the error.
	//
	// This is initially unset; if it remains unset by the time
	// Send is invoked, and the error has a stacktrace, the first
	// non-library frame in the stacktrace will be considered the
	// culprit.
	Culprit string

	// Transaction is the transaction to which the error correspoonds,
	// if any. If this is set, the error's Send method must be called
	// before the transaction's End method.
	Transaction *Transaction

	// Timestamp records the time at which the error occurred.
	// This is set when the Error object is created, but may
	// be overridden any time before the Send method is called.
	Timestamp time.Time

	// Handled records whether or not the error was handled. This
	// only applies to "exception" errors (errors created with
	// NewError, or Recovered), and is ignored by "log" errors.
	Handled bool

	// Context holds the context for this error.
	Context Context
	// contains filtered or unexported fields
}

Error describes an error occurring in the monitored service.

func CaptureError

func CaptureError(ctx context.Context, err error) *Error

CaptureError returns a new Error related to the sampled transaction present in the context, if any, and calls its SetException method with the given error. The Error.Handled field will be set to true, and a stacktrace set.

If there is no transaction in the context, or it is not being sampled, CaptureError returns nil. As a convenience, if the provided error is nil, then CaptureError will also return nil.

func (*Error) Send

func (e *Error) Send()

Send enqueues the error for sending to the Elastic APM server. The Error must not be used after this.

func (*Error) SetStacktrace

func (e *Error) SetStacktrace(skip int)

SetStacktrace sets the stacktrace for the error, skipping the first skip number of frames, excluding the SetStacktrace function.

type ErrorID added in v0.5.0

type ErrorID [16]byte

ErrorID uniquely identifies an error.

func (ErrorID) String added in v0.5.0

func (id ErrorID) String() string

String returns id in the canonical v4 UUID hex-encoded format.

type ErrorLogRecord

type ErrorLogRecord struct {
	// Message holds the message for the log record,
	// e.g. "failed to connect to %s".
	//
	// If this is empty, "[EMPTY]" will be used.
	Message string

	// MessageFormat holds the non-interpolated format
	// of the log record, e.g. "failed to connect to %s".
	//
	// This is optional.
	MessageFormat string

	// Level holds the severity level of the log record.
	//
	// This is optional.
	Level string

	// LoggerName holds the name of the logger used.
	//
	// This is optional.
	LoggerName string
}

ErrorLogRecord holds details of an error log record.

type GatherMetricsFunc added in v0.5.0

type GatherMetricsFunc func(context.Context, *Metrics) error

GatherMetricsFunc is a function type implementing MetricsGatherer.

func (GatherMetricsFunc) GatherMetrics added in v0.5.0

func (f GatherMetricsFunc) GatherMetrics(ctx context.Context, m *Metrics) error

GatherMetrics calls f(ctx, m).

type Logger

type Logger interface {
	// Debugf logs a message at debug level.
	Debugf(format string, args ...interface{})

	// Errorf logs a message at error level.
	Errorf(format string, args ...interface{})
}

Logger is an interface for logging, used by the tracer to log tracer errors and other interesting events.

type MetricLabel added in v0.5.0

type MetricLabel struct {
	// Name is the label name.
	Name string

	// Value is the label value.
	Value string
}

MetricLabel is a name/value pair for labeling metrics.

type Metrics added in v0.5.0

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

Metrics holds a set of metrics.

func (*Metrics) Add added in v0.5.0

func (m *Metrics) Add(name string, labels []MetricLabel, value float64)

Add adds a metric with the given name, labels, and value, The labels are expected to be sorted lexicographically.

type MetricsGatherer added in v0.5.0

type MetricsGatherer interface {
	// GatherMetrics gathers metrics and adds them to m.
	//
	// If ctx.Done() is signaled, gathering should be aborted and
	// ctx.Err() returned. If GatherMetrics returns an error, it
	// will be logged, but otherwise there is no effect; the
	// implementation must take care not to leave m in an invalid
	// state due to errors.
	GatherMetrics(ctx context.Context, m *Metrics) error
}

MetricsGatherer provides an interface for gathering metrics.

type RatioSampler

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

RatioSampler is a Sampler that samples probabilistically based on the given ratio within the range [0,1.0].

A ratio of 1.0 samples 100% of transactions, a ratio of 0.5 samples ~50%, and so on.

func NewRatioSampler

func NewRatioSampler(r float64, source rand.Source) *RatioSampler

NewRatioSampler returns a new RatioSampler with the given ratio and math/rand.Source. The source will be called from multiple goroutines, but the sampler will internally synchronise access to it; the source should not be used by any other goroutines.

If the ratio provided does not lie within the range [0,1.0], NewRatioSampler will panic.

func (*RatioSampler) Sample

func (s *RatioSampler) Sample(*Transaction) bool

Sample samples the transaction according to the configured ratio and pseudo-random source.

type Sampler

type Sampler interface {
	// Sample indicates whether or not the transaction
	// should be sampled. This method will be invoked
	// by calls to Tracer.StartTransaction, so it must
	// be goroutine-safe, and should avoid synchronization
	// as far as possible.
	Sample(*Transaction) bool
}

Sampler provides a means of sampling transactions.

type Span

type Span struct {
	Name      string
	Type      string
	Timestamp time.Time
	Duration  time.Duration
	Context   SpanContext
	// contains filtered or unexported fields
}

Span describes an operation within a transaction.

func SpanFromContext

func SpanFromContext(ctx context.Context) *Span

SpanFromContext returns the current Span in context, if any. The span must have been added to the context previously using either ContextWithSpan or SetSpanInContext.

func StartSpan

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

StartSpan starts and returns a new Span within the sampled transaction and parent span in the context, if any. If the span isn't dropped, it will be stored in the resulting context.

StartSpan always returns a non-nil Span. Its End method must be called when the span completes.

func (*Span) Dropped

func (s *Span) Dropped() bool

Dropped indicates whether or not the span is dropped, meaning it will not be included in any transaction. Spans are dropped by Transaction.StartSpan if the transaction is nil, non-sampled, or the transaction's max spans limit has been reached.

Dropped may be used to avoid any expensive computation required to set the span's context.

func (*Span) End

func (s *Span) End()

End marks the s as being complete; s must not be used after this.

If s.Duration has not been set, End will set it to the elapsed time since s.Timestamp.

func (*Span) SetStacktrace

func (s *Span) SetStacktrace(skip int)

SetStacktrace sets the stacktrace for the span, skipping the first skip number of frames, excluding the SetStacktrace function.

func (*Span) TraceContext added in v0.5.0

func (s *Span) TraceContext() TraceContext

TraceContext returns the span's TraceContext: its trace ID, span ID, and trace options. The values are undefined if distributed tracing is disabled. If the span is dropped, the trace ID and options will be zero.

type SpanContext

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

SpanContext provides methods for setting span context.

func (*SpanContext) SetDatabase

func (c *SpanContext) SetDatabase(db DatabaseSpanContext)

SetDatabase sets the span context for database-related operations.

func (*SpanContext) SetHTTPRequest added in v0.5.0

func (c *SpanContext) SetHTTPRequest(req *http.Request)

SetHTTPRequest sets the details of the HTTP request in the context.

This function relates to client requests. If the request URL contains user info, it will be removed and excluded from the stored URL.

type SpanID added in v0.5.0

type SpanID [8]byte

SpanID identifies a span within a trace.

func (SpanID) String added in v0.5.0

func (id SpanID) String() string

String returns id encoded as hex.

func (SpanID) Validate added in v0.5.0

func (id SpanID) Validate() error

Validate validates the span ID. This will return non-nil for a zero span ID.

type TraceContext added in v0.5.0

type TraceContext struct {
	// Trace identifies the trace forest.
	Trace TraceID

	// Span identifies a span: the parent span if this context
	// corresponds to an incoming request, or the current span
	// if this is an outgoing request.
	Span SpanID

	// Options holds the trace options propagated by the parent.
	Options TraceOptions
}

TraceContext holds trace context for an incoming or outgoing request.

type TraceID added in v0.5.0

type TraceID [16]byte

TraceID identifies a trace forest.

func (TraceID) String added in v0.5.0

func (id TraceID) String() string

String returns id encoded as hex.

func (TraceID) Validate added in v0.5.0

func (id TraceID) Validate() error

Validate validates the trace ID. This will return non-nil for a zero trace ID.

type TraceOptions added in v0.5.0

type TraceOptions uint8

TraceOptions describes the options for a trace.

func (TraceOptions) MaybeRecorded added in v0.5.0

func (o TraceOptions) MaybeRecorded() bool

MaybeRecorded reports whether or not the transaction/span may have been (or may be) recorded.

func (TraceOptions) Requested added in v0.5.0

func (o TraceOptions) Requested() bool

Requested reports whether or not it has been requested that this transaction/span be recorded.

func (TraceOptions) WithMaybeRecorded added in v0.5.0

func (o TraceOptions) WithMaybeRecorded(maybeRecorded bool) TraceOptions

WithMaybeRecorded changes the "recorded" flag, and returns the new options without modifying the original value.

func (TraceOptions) WithRequested added in v0.5.0

func (o TraceOptions) WithRequested(requested bool) TraceOptions

WithRequested changes the "requested" flag, and returns the new options without modifying the original value.

type Tracer

type Tracer struct {
	Transport transport.Transport
	Service   struct {
		Name        string
		Version     string
		Environment string
	}
	// contains filtered or unexported fields
}

Tracer manages the sampling and sending of transactions to Elastic APM.

Transactions are buffered until they are flushed (forcibly with a Flush call, or when the flush timer expires), or when the maximum transaction queue size is reached. Failure to send will be periodically retried. Once the queue limit has been reached, new transactions will replace older ones in the queue.

Errors are sent as soon as possible, but will buffered and later sent in bulk if the tracer is busy, or otherwise cannot send to the server, e.g. due to network failure. There is a limit to the number of errors that will be buffered, and once that limit has been reached, new errors will be dropped until the queue is drained.

The exported fields be altered or replaced any time up until any Tracer methods have been invoked.

Example

ExampleTracer shows how to use the Tracer API

package main

import (
	"compress/gzip"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/http/httptest"
	"os"
	"sync"
	"time"

	"github.com/elastic/apm-agent-go"
	"github.com/elastic/apm-agent-go/transport"
)

// ExampleTracer shows how to use the Tracer API
func main() {
	var r recorder
	server := httptest.NewServer(&r)
	defer server.Close()

	// ELASTIC_APM_SERVER_URL should typically set in the environment
	// when the process is started. The InitDefault call below is only
	// required in this case because the environment variable is set
	// after the program has been initialized.
	os.Setenv("ELASTIC_APM_SERVER_URL", server.URL)
	defer os.Unsetenv("ELASTIC_APM_SERVER_URL")
	transport.InitDefault()

	const serviceName = "service-name"
	const serviceVersion = "1.0.0"
	tracer, err := elasticapm.NewTracer(serviceName, serviceVersion)
	if err != nil {
		log.Fatal(err)
	}
	defer tracer.Close()

	// api is a very basic API handler, to demonstrate the usage
	// of the tracer. api.handlerOrder creates a transaction for
	// every call; api.handleOrder calls through to storeOrder,
	// which adds a span to the transaction.
	api := &api{tracer: tracer}
	api.handleOrder(context.Background(), "fish fingers")
	api.handleOrder(context.Background(), "detergent")

	// The tracer will queue transactions to be sent at a later time,
	// or when the queue becomes full. The interval and queue size
	// can both be configured by setting the environment variables
	// ELASTIC_APM_FLUSH_INTERVAL and ELASTIC_APM_MAX_QUEUE_SIZE
	// respectively. Alternatively, the tracer's SetFlushInterval
	// and SetMaxQueueSize methods can be used.
	tracer.Flush(nil)

	fmt.Println("number of payloads:", len(r.payloads))
	p0 := r.payloads[0]
	service := p0["service"].(map[string]interface{})
	agent := service["agent"].(map[string]interface{})
	language := service["language"].(map[string]interface{})
	runtime := service["runtime"].(map[string]interface{})
	transactions := p0["transactions"].([]interface{})
	fmt.Println("  service name:", service["name"])
	fmt.Println("  service version:", service["version"])
	fmt.Println("  agent name:", agent["name"])
	fmt.Println("  language name:", language["name"])
	fmt.Println("  runtime name:", runtime["name"])
	fmt.Println("  number of transactions:", len(transactions))
	for i := range transactions {
		t := transactions[i].(map[string]interface{})
		fmt.Println("    transaction name:", t["name"])
		fmt.Println("    transaction type:", t["type"])
		fmt.Println("    transaction context:", t["context"])
		spans := t["spans"].([]interface{})
		fmt.Println("    number of spans:", len(spans))
		s0 := spans[0].(map[string]interface{})
		fmt.Println("      span name:", s0["name"])
		fmt.Println("      span type:", s0["type"])
	}

}

type api struct {
	tracer *elasticapm.Tracer
}

func (api *api) handleOrder(ctx context.Context, product string) {
	tx := api.tracer.StartTransaction("order", "request")
	defer tx.End()
	ctx = elasticapm.ContextWithTransaction(ctx, tx)

	tx.Context.SetCustom("product", product)

	time.Sleep(10 * time.Millisecond)
	storeOrder(ctx, product)
	time.Sleep(20 * time.Millisecond)
}

func storeOrder(ctx context.Context, product string) {
	span, _ := elasticapm.StartSpan(ctx, "store_order", "rpc")
	defer span.End()

	time.Sleep(50 * time.Millisecond)
}

type recorder struct {
	mu       sync.Mutex
	payloads []map[string]interface{}
}

func (r *recorder) count() int {
	r.mu.Lock()
	defer r.mu.Unlock()
	return len(r.payloads)
}

func (r *recorder) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	var body io.Reader = req.Body
	if req.Header.Get("Content-Encoding") == "gzip" {
		r, err := gzip.NewReader(body)
		if err != nil {
			panic(err)
		}
		body = r
	}
	var m map[string]interface{}
	if err := json.NewDecoder(body).Decode(&m); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
	r.mu.Lock()
	r.payloads = append(r.payloads, m)
	r.mu.Unlock()
}
Output:

number of payloads: 1
  service name: service-name
  service version: 1.0.0
  agent name: go
  language name: go
  runtime name: gc
  number of transactions: 2
    transaction name: order
    transaction type: request
    transaction context: map[custom:map[product:fish fingers]]
    number of spans: 1
      span name: store_order
      span type: rpc
    transaction name: order
    transaction type: request
    transaction context: map[custom:map[product:detergent]]
    number of spans: 1
      span name: store_order
      span type: rpc
var (
	// DefaultTracer is the default global Tracer, set at package
	// initialization time, configured via environment variables.
	//
	// This will always be initialized to a non-nil value. If any
	// of the environment variables are invalid, the corresponding
	// errors will be logged to stderr and the default values will
	// be used instead.
	DefaultTracer *Tracer
)

func NewTracer

func NewTracer(serviceName, serviceVersion string) (*Tracer, error)

NewTracer returns a new Tracer, using the default transport, initializing a Service with the specified name and version, or taking the service name and version from the environment if unspecified.

If serviceName is empty, then the service name will be defined using the ELASTIC_APM_SERVER_NAME environment variable.

func (*Tracer) Active

func (t *Tracer) Active() bool

Active reports whether the tracer is active. If the tracer is inactive, no transactions or errors will be sent to the Elastic APM server.

func (*Tracer) CaptureHTTPRequestBody

func (t *Tracer) CaptureHTTPRequestBody(req *http.Request) *BodyCapturer

CaptureHTTPRequestBody replaces req.Body and returns a possibly nil BodyCapturer which can later be passed to Context.SetHTTPRequestBody for setting the request body in a transaction or error context. If the tracer is not configured to capture HTTP request bodies, then req.Body is left alone and nil is returned.

This must be called before the request body is read.

func (*Tracer) Close

func (t *Tracer) Close()

Close closes the Tracer, preventing transactions from being sent to the APM server.

func (*Tracer) Flush

func (t *Tracer) Flush(abort <-chan struct{})

Flush waits for the Tracer to flush any transactions and errors it currently has queued to the APM server, the tracer is stopped, or the abort channel is signaled.

func (*Tracer) NewError

func (t *Tracer) NewError(err error) *Error

NewError returns a new Error with details taken from err. NewError will panic if called with a nil error.

The exception message will be set to err.Error(). The exception module and type will be set to the package and type name of the cause of the error, respectively, where the cause has the same definition as given by github.com/pkg/errors.

If err implements

type interface {
    StackTrace() github.com/pkg/errors.StackTrace
}

or

type interface {
    StackTrace() []stacktrace.Frame
}

then one of those will be used to set the error stacktrace. Otherwise, NewError will take a stacktrace.

If err implements

type interface {Type() string}

then that will be used to set the error type.

If err implements

type interface {Code() string}

or

type interface {Code() float64}

then one of those will be used to set the error code.

func (*Tracer) NewErrorLog

func (t *Tracer) NewErrorLog(r ErrorLogRecord) *Error

NewErrorLog returns a new Error for the given ErrorLogRecord.

The resulting Error's stacktrace will not be set. Call the SetStacktrace method to set it, if desired.

If r.Message is empty, "[EMPTY]" will be used.

func (*Tracer) Recover

func (t *Tracer) Recover(tx *Transaction)

Recover recovers panics, sending them as errors to the Elastic APM server. Recover is expected to be used in a deferred call.

Recover simply calls t.Recovered(v, tx), where v is the recovered value, and then calls the resulting Error's Send method.

func (*Tracer) Recovered

func (t *Tracer) Recovered(v interface{}, tx *Transaction) *Error

Recovered creates an Error with t.NewError(err), where err is either v (if v implements error), or otherwise fmt.Errorf("%v", v). The value v is expected to have come from a panic.

The resulting error's Transaction will be set to tx,

func (*Tracer) RegisterMetricsGatherer added in v0.5.0

func (t *Tracer) RegisterMetricsGatherer(g MetricsGatherer) func()

RegisterMetricsGatherer registers g for periodic (or forced) metrics gathering by t.

RegisterMetricsGatherer returns a function which will deregister g. It may safely be called multiple times.

func (*Tracer) SendMetrics added in v0.5.0

func (t *Tracer) SendMetrics(abort <-chan struct{})

SendMetrics forces the tracer to gather and send metrics immediately, blocking until the metrics have been sent or the abort channel is signalled.

func (*Tracer) SetCaptureBody

func (t *Tracer) SetCaptureBody(mode CaptureBodyMode)

SetCaptureBody sets the HTTP request body capture mode.

func (*Tracer) SetContextSetter

func (t *Tracer) SetContextSetter(setter stacktrace.ContextSetter)

SetContextSetter sets the stacktrace.ContextSetter to be used for setting stacktrace source context. If nil (which is the initial value), no context will be set.

func (*Tracer) SetFlushInterval

func (t *Tracer) SetFlushInterval(d time.Duration)

SetFlushInterval sets the flush interval -- the amount of time to wait before flushing enqueued transactions to the APM server.

func (*Tracer) SetLogger

func (t *Tracer) SetLogger(logger Logger)

SetLogger sets the Logger to be used for logging the operation of the tracer.

func (*Tracer) SetMaxErrorQueueSize

func (t *Tracer) SetMaxErrorQueueSize(n int)

SetMaxErrorQueueSize sets the maximum error queue size -- the maximum number of errors to buffer before they will start getting dropped. If set to a non-positive value, the queue size is unlimited.

func (*Tracer) SetMaxSpans

func (t *Tracer) SetMaxSpans(n int)

SetMaxSpans sets the maximum number of spans that will be added to a transaction before dropping. If set to a non-positive value, the number of spans is unlimited.

func (*Tracer) SetMaxTransactionQueueSize

func (t *Tracer) SetMaxTransactionQueueSize(n int)

SetMaxTransactionQueueSize sets the maximum transaction queue size -- the maximum number of transactions to buffer before flushing to the APM server. If set to a non-positive value, the queue size is unlimited.

func (*Tracer) SetMetricsInterval added in v0.5.0

func (t *Tracer) SetMetricsInterval(d time.Duration)

SetMetricsInterval sets the metrics interval -- the amount of time in between metrics samples being gathered.

func (*Tracer) SetSampler

func (t *Tracer) SetSampler(s Sampler)

SetSampler sets the sampler the tracer. It is valid to pass nil, in which case all transactions will be sampled.

func (*Tracer) SetSanitizedFieldNames

func (t *Tracer) SetSanitizedFieldNames(patterns ...string) error

SetSanitizedFieldNames sets the patterns that will be used to match cookie and form field names for sanitization. Fields matching any of the the supplied patterns will have their values redacted. If SetSanitizedFieldNames is called with no arguments, then no fields will be redacted.

func (*Tracer) SetSpanFramesMinDuration

func (t *Tracer) SetSpanFramesMinDuration(d time.Duration)

SetSpanFramesMinDuration sets the minimum duration for a span after which we will capture its stack frames.

func (*Tracer) StartTransaction

func (t *Tracer) StartTransaction(name, transactionType string) *Transaction

StartTransaction returns a new Transaction with the specified name and type, and with the start time set to the current time. This is equivalent to calling StartTransactionOptions with a zero TransactionOptions.

func (*Tracer) StartTransactionOptions added in v0.5.0

func (t *Tracer) StartTransactionOptions(name, transactionType string, opts TransactionOptions) *Transaction

StartTransactionOptions returns a new Transaction with the specified name, type, and options.

func (*Tracer) Stats

func (t *Tracer) Stats() TracerStats

Stats returns the current TracerStats. This will return the most recent values even after the tracer has been closed.

type TracerStats

type TracerStats struct {
	Errors              TracerStatsErrors
	ErrorsSent          uint64
	ErrorsDropped       uint64
	TransactionsSent    uint64
	TransactionsDropped uint64
}

TracerStats holds statistics for a Tracer.

type TracerStatsErrors

type TracerStatsErrors struct {
	SetContext       uint64
	SendTransactions uint64
	SendErrors       uint64
}

TracerStatsErrors holds error statistics for a Tracer.

type Transaction

type Transaction struct {
	Name      string
	Type      string
	Timestamp time.Time
	Duration  time.Duration
	Context   Context
	Result    string
	// contains filtered or unexported fields
}

Transaction describes an event occurring in the monitored service.

func TransactionFromContext

func TransactionFromContext(ctx context.Context) *Transaction

TransactionFromContext returns the current Transaction in context, if any. The transaction must have been added to the context previously using either ContextWithTransaction or SetTransactionInContext.

func (*Transaction) Discard

func (tx *Transaction) Discard()

Discard discards a previously started transaction. The Transaction must not be used after this.

func (*Transaction) End

func (tx *Transaction) End()

End enqueues tx for sending to the Elastic APM server; tx must not be used after this.

If tx.Duration has not been set, End will set it to the elapsed time since tx.Timestamp.

func (*Transaction) Sampled

func (tx *Transaction) Sampled() bool

Sampled reports whether or not the transaction is sampled.

func (*Transaction) StartSpan

func (tx *Transaction) StartSpan(name, spanType string, parent *Span) *Span

StartSpan starts and returns a new Span within the transaction, with the specified name, type, and optional parent span, and with the start time set to the current time relative to the transaction's timestamp.

StartSpan always returns a non-nil Span. Its End method must be called when the span completes.

func (*Transaction) TraceContext added in v0.5.0

func (tx *Transaction) TraceContext() TraceContext

TraceContext returns the transaction's TraceContext: its trace ID, span ID, and trace options. The values are undefined if distributed tracing is disabled.

type TransactionOptions added in v0.5.0

type TransactionOptions struct {
	// TraceContext holds the TraceContext for a new transaction. If this is
	// zero, and distributed tracing is enabled, a new trace will be started.
	//
	// TraceContext is ignored if distributed tracing is disabled.
	TraceContext TraceContext

	// Start is the start time of the transaction. If this has the
	// zero value, time.Now() will be used instead.
	Start time.Time
}

TransactionOptions holds options for Tracer.StartTransactionOptions.

Directories

Path Synopsis
internal
fastjson
Package fastjson provides a code generator and library for fast JSON encoding, limited to what apm-agent-go requires.
Package fastjson provides a code generator and library for fast JSON encoding, limited to what apm-agent-go requires.
krtext
Package text provides rudimentary functions for manipulating text in paragraphs.
Package text provides rudimentary functions for manipulating text in paragraphs.
pretty
Package pretty provides pretty-printing for Go values.
Package pretty provides pretty-printing for Go values.
sqlutil
Package sqlutil provides utilities to SQL-related instrumentation modules.
Package sqlutil provides utilities to SQL-related instrumentation modules.
Package model provides the Elastic APM model types.
Package model provides the Elastic APM model types.
module
apmecho
Package apmecho provides middleware for the Echo framework, for tracing HTTP requests.
Package apmecho provides middleware for the Echo framework, for tracing HTTP requests.
apmgin
Package apmgin provides middleware for the Gin framework, for tracing HTTP requests.
Package apmgin provides middleware for the Gin framework, for tracing HTTP requests.
apmgocql
Package apmgocql provides an observer for tracing gocql (Cassandra) query spans.
Package apmgocql provides an observer for tracing gocql (Cassandra) query spans.
apmgorm
Package apmgorm provides wrappers for tracing GORM operations.
Package apmgorm provides wrappers for tracing GORM operations.
apmgorm/dialects/mysql
Package apmgormmysql imports the gorm mysql dialect package, and also registers the mysql driver with apmsql.
Package apmgormmysql imports the gorm mysql dialect package, and also registers the mysql driver with apmsql.
apmgorm/dialects/postgres
Package apmgormpostgres imports the gorm postgres dialect package, and also registers the lib/pq driver with apmsql.
Package apmgormpostgres imports the gorm postgres dialect package, and also registers the lib/pq driver with apmsql.
apmgorm/dialects/sqlite
Package apmgormsqlite imports the gorm sqlite dialect package, and also registers the sqlite3 driver with apmsql.
Package apmgormsqlite imports the gorm sqlite dialect package, and also registers the sqlite3 driver with apmsql.
apmgrpc
Package apmgrpc provides interceptors for tracing gRPC.
Package apmgrpc provides interceptors for tracing gRPC.
apmhttp
Package apmhttp provides a tracing middleware http.Handler for servers, and a tracing http.RoundTripper for clients.
Package apmhttp provides a tracing middleware http.Handler for servers, and a tracing http.RoundTripper for clients.
apmlambda
Package apmlambda provides tracing for AWS Lambda functions.
Package apmlambda provides tracing for AWS Lambda functions.
apmot
Package apmot provides an Elastic APM implementation of the OpenTracing API.
Package apmot provides an Elastic APM implementation of the OpenTracing API.
apmsql
Package apmsql provides wrappers for tracing SQL query spans.
Package apmsql provides wrappers for tracing SQL query spans.
apmsql/mysql
Package apmmysql registers the "mysql" driver with apmsql, so that you can trace go-sql-driver/mysql database connections.
Package apmmysql registers the "mysql" driver with apmsql, so that you can trace go-sql-driver/mysql database connections.
apmsql/pq
Package apmpq registers the "postgres" driver with apmsql, so that you can trace lib/pq database connections.
Package apmpq registers the "postgres" driver with apmsql, so that you can trace lib/pq database connections.
apmsql/sqlite3
Package apmsqlite3 registers the "sqlite3" driver with apmsql, so that you can trace sqlite3 database connections.
Package apmsqlite3 registers the "sqlite3" driver with apmsql, so that you can trace sqlite3 database connections.
Package stacktrace provides a simplified stack frame type, functions for obtaining stack frames, and related utilities.
Package stacktrace provides a simplified stack frame type, functions for obtaining stack frames, and related utilities.
Package transport provides an interface and implementation for transporting data to the Elastic APM server.
Package transport provides an interface and implementation for transporting data to the Elastic APM server.
transporttest
Package transporttest provides implementations of transport.Transport for testing purposes.
Package transporttest provides implementations of transport.Transport for testing purposes.

Jump to

Keyboard shortcuts

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