API Documentation
editAPI Documentation
editBelow we cover the most commonly used parts of the API.
The Go agent is documented using standard godoc. For complete documentation, refer to the documentation at godoc.org/github.com/elastic/apm-agent-go, or by using the "godoc" tool.
Tracer API
editThe initial point of contact your application will have with the Go agent
is the elasticapm.Tracer
type, which provides methods for reporting
transactions and errors.
To make instrumentation simpler the Go agent provides a pre-initialized
tracer, elasticapm.DefaultTracer
. This tracer is always initialized and
available for use. This tracer is configured with environment variables;
see Configuration for details.
import ( "github.com/elastic/apm-agent-go" // elasticapm ) func main() { tracer := elasticapm.DefaultTracer ... }
Transactions
editfunc (*Tracer) StartTransaction(name, type string) *Transaction
editStartTransaction returns a new Transaction with the specified name and type,
and with the start time set to the current time. Time timestamp can be overridden
by updating the resulting object’s Timestamp
field.
This method should be called at the beginning of a transaction such as a web or RPC request. e.g.:
transaction := elasticapm.DefaultTracer.StartTransaction("GET /", "request")
Transactions will be grouped by type and name in the Elastic APM UI.
After starting a transaction, you can record a result and add context to further describe the transaction.
transaction.Result = "Success" transaction.Context.SetTag("region", "us-east-1") transaction.Context.SetCustom("key", "value")
See Context for more details on setting transaction context.
func (*Transaction) End()
editEnd enqueues the transaction for sending to the Elastic APM server. The Transaction must not be used after this.
The transaction’s duration will be calculated as the amount of time elapsed since the transaction was started until this call. To override this behaviour, the transaction’s Duration field may be set before calling End.
transaction.End()
func ContextWithTransaction(context.Context, *Transaction) context.Context
editContextWithTransaction adds the transaction to the context, and returns the resulting context.
The transaction can be retrieved using elasticapm.TransactionFromContext. The context may also be passed into elasticapm.StartSpan, which uses TransactionFromContext under the covers to create a span as a child of the transaction.
func TransactionFromContext(context.Context) *Transaction
editTransactionFromContext returns a transaction previously stored in the context using elasticapm.ContextWithTransaction, or nil if the context does not contain a transaction.
Spans
editTo describe an activity within a transaction, we create spans. The Go agent has built-in support for generating spans for some activities, such as database queries. You can use the API to report spans specific to your application.
func (*Transaction) StartSpan(name, spanType string, parent *Span) *Span
editStartSpan 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.
If the transaction is sampled, then the span’s ID will be set, and its stacktrace will be set if the tracer is configured accordingly. If the transaction is not sampled, then the returned span will be silently discarded when its End method is called. You can avoid any unnecessary computation for these dropped spans by calling its Dropped method.
As a convenience, it is valid to create a span on a nil Transaction; the resulting span will be non-nil and safe for use, but will not be reported to the APM server.
span := tx.StartSpan("SELECT FROM foo", "db.mysql.query", nil)
func StartSpan(ctx context.Context, name, spanType string) (*Span, context.Context)
editStartSpan 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 indluded in the resulting context.
span, ctx := elasticapm.StartSpan(ctx, "SELECT FROM foo", "db.mysql.query")
func (*Span) End()
editEnd marks the span as complete; it must not be used after this.
The span’s duration will be calculated as the amount of time elapsed since the span was started until this call. To override this behaviour, the span’s Duration field may be set before calling End.
func (*Span) Dropped() bool
editDropped indicates whether or not the span is dropped, meaning it will not be reported to the APM server. Spans are dropped when the created via a nil or non-sampled transaction, or one whose max spans limit has been reached.
func ContextWithSpan(context.Context, *Span) context.Context
editContextWithSpan adds the span to the context, and returns the resulting context.
The span can be retrieved using elasticapm.SpanFromContext. The context may also be passed into elasticapm.StartSpan, which uses SpanFromContext under the covers to create another span as a child of the span.
func SpanFromContext(context.Context) *Span
editSpanFromContext returns a span previously stored in the context using elasticapm.ContextWithSpan, or nil if the context does not contain a span.
Context
editWhen reporting transactions and errors you can provide context to describe those events. Built-in instrumentation will typically provide some context, e.g. the URL and remote address for an HTTP request. You can also provide custom context and tags.
func (*Context) SetTag(key, value string)
editSetTag tags the transaction or error with the given key and value. The
key must not contain any special characters (.
, *
, or "
). Values
longer than 1024 characters will be truncated. Tags will be indexed in
Elasticsearch as keyword fields.
func (*Context) SetCustom(key string, value interface{})
editSetCustom associates arbitrary context with the transaction or error. The
only restriction is that the name may not contain any special characters
(.
, *
, or "
), and the value must be JSON-encodable. Custom context
will not be indexed in Elasticsearch, but will be included in the document.
func (*Context) SetUsername(username string)
editSetUsername records the username of the user associated with the transaction.
func (*Context) SetUserID(id string)
editSetUserID records the ID of the user associated with the transaction.
func (*Context) SetUserEmail(email string)
editSetUserEmail records the email address of the user associated with the transaction.
Errors
editElastic APM provides two methods of capturing an error event: reporting an error log record, and reporting an "exception" (either a panic or an error in Go parlance).
func (*Tracer) NewError(error) *Error
editNewError returns a new Error with details taken from err.
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.
e := elasticapm.DefaultTracer.NewError(err) ... e.Send()
The provided error can implement any of several interfaces to provide additional information:
// Errors implementing ErrorsStacktracer will have their stacktrace // set based on the result of the StackTrace method. type ErrorsStacktracer interface { StackTrace() github.com/pkg/errors.StackTrace } // Errors implementing Stacktracer will have their stacktrace // set based on the result of the StackTrace method. type Stacktracer interface { StackTrace() []github.com/elastic/apm-agent-go/stacktrace.Frame } // Errors implementing Typer will have a "type" field set to the // result of the Type method. type Typer interface { Type() string } // Errors implementing StringCoder will have a "code" field set to the // result of the Code method. type StringCoder interface { Code() string } // Errors implementing NumberCoder will have a "code" field set to the // result of the Code method. type NumberCoder interface { Code() float64 }
Errors created by with NewError will have their ID field populated with a UUID. This can be used in your application for correlation.
func (*Tracer) NewErrorLog(ErrorLogRecord) *Error
editNewErrorLog returns a new Error for the given 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 }
The resulting Error’s stacktrace will not be set. Call the SetStacktrace method to set it, if desired.
e := elasticapm.DefaultTracer.NewErrorLog(elasticapm.ErrorLogRecord{ Message: "Somebody set up us the bomb.", }) ... e.Send()
func (*Error) Send()
editSend enqueues the error for sending to the Elastic APM server. The Error must not be used after this.
func (*Tracer) Recover(*Transaction)
editRecover recovers panics, sending them as errors to the Elastic APM server. Recover is expected to be
used in a deferred call. Recover calls the tracer’s Recovered
method with the recovered value and
transaction provided to Recover, and calls the resulting Error’s Send method.
tx := elasticapm.DefaultTracer.StartTransaction(...) defer tx.End() defer elasticapm.DefaultTracer.Recover(tx)
func (*Tracer) Recovered(interface{}, *Transaction) *Error
editRecovered returns an Error from the recovered value, optionally associating it with a transaction.
The error is not sent; it is the responsibility of the caller to set the error’s context as desired,
and then call its Send
method.
tx := elasticapm.DefaultTracer.StartTransaction(...) defer tx.End() defer elasticapm.DefaultTracer.Recover(tx)
func CaptureError(context.Context, error) *Error
editCaptureError 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.
if err != nil { e := elasticapm.CaptureError(ctx, err) e.Send() }
Error Context
editErrors can be associated with context just like transactions. See Context for details.
In addition, errors can be associated with a transaction by setting the Transaction
field to
an active Transaction object:
tx := elasticapm.DefaultTracer.StartTransaction("GET /foo", "request") defer tx.End() e := elasticapm.DefaultTracer.NewError(err) e.Transaction = tx e.Send()