Documentation ¶
Overview ¶
Package apm provides an API for tracing transactions and capturing errors, sending the data to Elastic APM.
Index ¶
- Constants
- func ContextWithBodyCapturer(parent context.Context, bc *BodyCapturer) context.Context
- func ContextWithSpan(parent context.Context, s *Span) context.Context
- func ContextWithTransaction(parent context.Context, t *Transaction) context.Context
- func DetachedContext(ctx context.Context) context.Context
- func RegisterErrorDetailer(e ErrorDetailer)
- func RegisterTypeErrorDetailer(t reflect.Type, e ErrorDetailer)
- func TraceFormatter(ctx context.Context) fmt.Formatter
- type BodyCapturer
- type CaptureBodyMode
- type Context
- func (c *Context) SetCustom(key string, value interface{})
- func (c *Context) SetFramework(name, version string)
- func (c *Context) SetHTTPRequest(req *http.Request)
- func (c *Context) SetHTTPRequestBody(bc *BodyCapturer)
- func (c *Context) SetHTTPResponseHeaders(h http.Header)
- func (c *Context) SetHTTPStatusCode(statusCode int)
- func (c *Context) SetLabel(key string, value interface{})
- func (c *Context) SetTag(key, value string)
- func (c *Context) SetUserEmail(email string)
- func (c *Context) SetUserID(id string)
- func (c *Context) SetUsername(username string)
- type DatabaseSpanContext
- type DestinationCloudSpanContext
- type DestinationServiceSpanContext
- type Error
- type ErrorData
- type ErrorDetailer
- type ErrorDetailerFunc
- type ErrorDetails
- type ErrorID
- type ErrorLogRecord
- type ExtendedSampler
- type GatherMetricsFunc
- type Logger
- type MessageSpanContext
- type MetricLabel
- type Metrics
- type MetricsGatherer
- type SampleParams
- type SampleResult
- type Sampler
- type Span
- type SpanContext
- func (c *SpanContext) SetDatabase(db DatabaseSpanContext)
- func (c *SpanContext) SetDatabaseRowsAffected(n int64)
- func (c *SpanContext) SetDestinationAddress(addr string, port int)
- func (c *SpanContext) SetDestinationCloud(cloud DestinationCloudSpanContext)
- func (c *SpanContext) SetDestinationService(service DestinationServiceSpanContext)
- func (c *SpanContext) SetHTTPRequest(req *http.Request)
- func (c *SpanContext) SetHTTPStatusCode(statusCode int)
- func (c *SpanContext) SetLabel(key string, value interface{})
- func (c *SpanContext) SetMessage(message MessageSpanContext)
- func (c *SpanContext) SetTag(key, value string)
- type SpanData
- type SpanID
- type SpanOptions
- type TraceContext
- type TraceID
- type TraceOptions
- type TraceState
- type TraceStateEntry
- type Tracer
- func (t *Tracer) Active() bool
- func (t *Tracer) CaptureHTTPRequestBody(req *http.Request) *BodyCapturer
- func (t *Tracer) Close()
- func (t *Tracer) Flush(abort <-chan struct{})
- func (t *Tracer) IgnoredTransactionURL(url *url.URL) bool
- func (t *Tracer) NewError(err error) *Error
- func (t *Tracer) NewErrorLog(r ErrorLogRecord) *Error
- func (t *Tracer) Recording() bool
- func (t *Tracer) Recovered(v interface{}) *Error
- func (t *Tracer) RegisterMetricsGatherer(g MetricsGatherer) func()
- func (t *Tracer) SendMetrics(abort <-chan struct{})
- func (t *Tracer) SetCaptureBody(mode CaptureBodyMode)
- func (t *Tracer) SetCaptureHeaders(capture bool)
- func (t *Tracer) SetConfigWatcher(w apmconfig.Watcher)
- func (t *Tracer) SetContextSetter(setter stacktrace.ContextSetter)
- func (t *Tracer) SetExitSpanMinDuration(v time.Duration)
- func (t *Tracer) SetIgnoreTransactionURLs(pattern string) error
- func (t *Tracer) SetLogger(logger Logger)
- func (t *Tracer) SetMaxSpans(n int)
- func (t *Tracer) SetMetricsInterval(d time.Duration)
- func (t *Tracer) SetRecording(r bool)
- func (t *Tracer) SetRequestDuration(d time.Duration)
- func (t *Tracer) SetSampler(s Sampler)
- func (t *Tracer) SetSanitizedFieldNames(patterns ...string) error
- func (t *Tracer) SetSpanCompressionEnabled(v bool)
- func (t *Tracer) SetSpanCompressionExactMatchMaxDuration(v time.Duration)
- func (t *Tracer) SetSpanCompressionSameKindMaxDuration(v time.Duration)
- func (t *Tracer) SetSpanFramesMinDuration(d time.Duration)
- func (t *Tracer) SetStackTraceLimit(limit int)
- func (t *Tracer) ShouldPropagateLegacyHeader() bool
- func (t *Tracer) StartSpan(name, spanType string, transactionID SpanID, opts SpanOptions) *Span
- func (t *Tracer) StartTransaction(name, transactionType string) *Transaction
- func (t *Tracer) StartTransactionOptions(name, transactionType string, opts TransactionOptions) *Transaction
- func (t *Tracer) Stats() TracerStats
- type TracerOptions
- type TracerStats
- type TracerStatsErrors
- type Transaction
- func (tx *Transaction) Discard()
- func (tx *Transaction) End()
- func (tx *Transaction) EnsureParent() SpanID
- func (tx *Transaction) ParentID() SpanID
- func (tx *Transaction) Sampled() bool
- func (tx *Transaction) ShouldPropagateLegacyHeader() bool
- func (tx *Transaction) StartSpan(name, spanType string, parent *Span) *Span
- func (tx *Transaction) StartSpanOptions(name, spanType string, opts SpanOptions) *Span
- func (tx *Transaction) TraceContext() TraceContext
- type TransactionData
- type TransactionOptions
- type WarningLogger
Examples ¶
Constants ¶
const (
// AgentVersion is the Elastic APM Go Agent version.
AgentVersion = "1.15.0"
)
Variables ¶
This section is empty.
Functions ¶
func ContextWithBodyCapturer ¶ added in v1.12.0
func ContextWithBodyCapturer(parent context.Context, bc *BodyCapturer) context.Context
ContextWithBodyCapturer returns a copy of parent in which the given body capturer is stored, associated with the key bodyCapturerKey.
func ContextWithSpan ¶
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.
func DetachedContext ¶ added in v1.3.0
DetachedContext returns a new context detached from the lifetime of ctx, but which still returns the values of ctx.
DetachedContext can be used to maintain the trace context required to correlate events, but where the operation is "fire-and-forget", and should not be affected by the deadline or cancellation of ctx.
func RegisterErrorDetailer ¶ added in v1.3.0
func RegisterErrorDetailer(e ErrorDetailer)
RegisterErrorDetailer registers e in the global list of ErrorDetailers.
Each ErrorDetailer registered in this way will be called, in the order registered, for each error created via Tracer.NewError or Tracer.NewErrorLog.
RegisterErrorDetailer must not be called during tracer operation; it is intended to be called at package init time.
func RegisterTypeErrorDetailer ¶ added in v1.3.0
func RegisterTypeErrorDetailer(t reflect.Type, e ErrorDetailer)
RegisterTypeErrorDetailer registers e to be called for any error with the concrete type t.
Each ErrorDetailer registered in this way will be called, in the order registered, for each error of type t created via Tracer.NewError or Tracer.NewErrorLog.
RegisterTypeErrorDetailer must not be called during tracer operation; it is intended to be called at package init time.
func TraceFormatter ¶ added in v1.6.0
TraceFormatter returns a fmt.Formatter that can be used to format the identifiers of the transaction and span in ctx.
The returned Formatter understands the following verbs:
%v: trace ID, transaction ID, and span ID (if existing), space-separated the plus flag (%+v) adds field names, e.g. "trace.id=... transaction.id=..." %t: trace ID (hex-encoded, or empty string if non-existent) the plus flag (%+T) adds the field name, e.g. "trace.id=..." %x: transaction ID (hex-encoded, or empty string if non-existent) the plus flag (%+t) adds the field name, e.g. "transaction.id=..." %s: span ID (hex-encoded, or empty string if non-existent) the plus flag (%+s) adds the field name, e.g. "span.id=..."
Example ¶
package main import ( "context" "log" "go.elastic.co/apm" "go.elastic.co/apm/apmtest" ) func main() { apmtest.WithTransaction(func(ctx context.Context) { span, ctx := apm.StartSpan(ctx, "name", "type") defer span.End() // The %+v format will add // // "trace.id=... transaction.id=... span.id=..." // // to the log output. log.Printf("ERROR [%+v] blah blah", apm.TraceFormatter(ctx)) }) }
Output:
Types ¶
type BodyCapturer ¶
type BodyCapturer struct {
// contains filtered or unexported fields
}
BodyCapturer is returned by Tracer.CaptureHTTPRequestBody to later be passed to Context.SetHTTPRequestBody.
Calling Context.SetHTTPRequestBody will reset req.Body to its original value, and invalidates the BodyCapturer.
func BodyCapturerFromContext ¶ added in v1.13.0
func BodyCapturerFromContext(ctx context.Context) *BodyCapturer
BodyCapturerFromContext returns the BodyCapturer in context, if any. The body capturer must have been added to the context previously using ContextWithBodyCapturer.
func (*BodyCapturer) Discard ¶ added in v1.5.0
func (bc *BodyCapturer) Discard()
Discard discards the body capturer: the original request body is replaced, and the body capturer is returned to a pool for reuse. The BodyCapturer must not be used after calling this.
Discard has no effect if bc is nil.
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.
NOTE this is entirely unrelated to the standard library's context.Context.
func (*Context) SetCustom ¶
SetCustom sets custom context.
Invalid characters ('.', '*', and '"') in the key will be replaced with an underscore. The value may be any JSON-encodable value.
Example ¶
package main import ( "context" "go.elastic.co/apm" ) func main() { var ctx context.Context // request context tx := apm.TransactionFromContext(ctx) tx.Context.SetCustom("key", "value") }
Output:
func (*Context) SetFramework ¶ added in v1.0.0
SetFramework sets the framework name and version in the context.
This is used for identifying the framework in which the context was created, such as Gin or Echo.
If the name is empty, this is a no-op. If version is empty, then it will be set to "unspecified".
func (*Context) SetHTTPRequest ¶
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. An explicit call to SetUsername always takes precedence.
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) SetHTTPResponseHeaders ¶
SetHTTPResponseHeaders sets the HTTP response headers in the context.
func (*Context) SetHTTPStatusCode ¶
SetHTTPStatusCode records the HTTP response status code.
If, when the transaction ends, its Outcome field has not been explicitly set, it will be set based on the status code: "success" if statusCode < 500, and "failure" otherwise.
func (*Context) SetLabel ¶ added in v1.6.0
SetLabel sets a label in the context.
Invalid characters ('.', '*', and '"') in the key will be replaced with underscores.
If the value is numerical or boolean, then it will be sent to the server as a JSON number or boolean; otherwise it will converted to a string, using `fmt.Sprint` if necessary. String values longer than 1024 characters will be truncated.
func (*Context) SetTag ¶
SetTag calls SetLabel(key, value).
SetTag is deprecated, and will be removed in a future major version.
func (*Context) SetUserEmail ¶ added in v1.0.0
SetUserEmail sets the email for the authenticated user.
Example ¶
package main import ( "context" "go.elastic.co/apm" ) func main() { var ctx context.Context // request context tx := apm.TransactionFromContext(ctx) tx.Context.SetUsername("admin@example.com") }
Output:
func (*Context) SetUserID ¶ added in v1.0.0
SetUserID sets the ID of the authenticated user.
Example ¶
package main import ( "context" "go.elastic.co/apm" ) func main() { var ctx context.Context // request context tx := apm.TransactionFromContext(ctx) tx.Context.SetUserID("1000") }
Output:
func (*Context) SetUsername ¶ added in v1.0.0
SetUsername sets the username of the authenticated user.
Example ¶
package main import ( "context" "go.elastic.co/apm" ) func main() { var ctx context.Context // request context tx := apm.TransactionFromContext(ctx) tx.Context.SetUsername("root") }
Output:
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 DestinationCloudSpanContext ¶ added in v1.12.0
type DestinationCloudSpanContext struct { // Region holds the destination cloud region. Region string }
DestinationCloudSpanContext holds contextual information about a destination cloud.
type DestinationServiceSpanContext ¶ added in v1.7.0
type DestinationServiceSpanContext struct { // Name holds a name for the destination service, which may be used // for grouping and labeling in service maps. Deprecated. Name string // Resource holds an identifier for a destination service resource, // such as a message queue. Resource string }
DestinationServiceSpanContext holds destination service span span.
type Error ¶
type Error struct { // ErrorData holds the error data. This field is set to nil when // the error's Send method is called. *ErrorData // contains filtered or unexported fields }
Error describes an error occurring in the monitored service.
func CaptureError ¶
CaptureError returns a new Error related to the sampled transaction and span present in the context, if any, and sets its exception info from err. The Error.Handled field will be set to true, and a stacktrace set either from err, or from the caller.
If the provided error is nil, then CaptureError will also return nil; otherwise a non-nil Error will always be returned. If there is no transaction or span in the context, then the returned Error's Send method will have no effect.
func (*Error) Cause ¶ added in v1.2.0
Cause returns original error assigned to Error, nil if Error or Error.cause is nil. https://godoc.org/github.com/pkg/errors#Cause
func (*Error) Error ¶ added in v1.2.0
Error returns string message for error. if Error or Error.cause is nil, "[EMPTY]" will be used.
func (*Error) Send ¶
func (e *Error) Send()
Send enqueues the error for sending to the Elastic APM server.
Send will set e.ErrorData to nil, so the error must not be modified after Send returns.
func (*Error) SetSpan ¶ added in v1.0.0
SetSpan sets TraceID, TransactionID, and ParentID to the span's IDs.
There is no need to call both SetTransaction and SetSpan. If you do call both, then SetSpan must be called second in order to set the error's ParentID correctly.
If any custom context has been recorded in s's transaction, it will also be carried across to e, but will not override any custom context already recorded on e.
func (*Error) SetStacktrace ¶
SetStacktrace sets the stacktrace for the error, skipping the first skip number of frames, excluding the SetStacktrace function.
func (*Error) SetTransaction ¶ added in v1.0.0
func (e *Error) SetTransaction(tx *Transaction)
SetTransaction sets TraceID, TransactionID, and ParentID to the transaction's IDs, and records the transaction's Type and whether or not it was sampled.
If any custom context has been recorded in tx, it will also be carried across to e, but will not override any custom context already recorded on e.
SetTransaction also has the effect of setting tx's default outcome to "failure", unless it is explicitly specified by the instrumentation.
type ErrorData ¶ added in v1.1.0
type ErrorData struct { // ID is the unique identifier of the error. This is set by // the various error constructors, and is exposed only so // the error ID can be logged or displayed to the user. ID ErrorID // TraceID is the unique identifier of the trace in which // this error occurred. If the error is not associated with // a trace, this will be the zero value. TraceID TraceID // TransactionID is the unique identifier of the transaction // in which this error occurred. If the error is not associated // with a transaction, this will be the zero value. TransactionID SpanID // ParentID is the unique identifier of the transaction or span // in which this error occurred. If the error is not associated // with a transaction or span, this will be the zero value. ParentID SpanID // 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 // 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 // is ignored by "log" errors with no associated error value. Handled bool // Context holds the context for this error. Context Context // contains filtered or unexported fields }
ErrorData holds the details for an error, and is embedded inside Error. When the error is sent, its ErrorData field will be set to nil.
type ErrorDetailer ¶ added in v1.3.0
type ErrorDetailer interface { // ErrorDetails is called to update or alter details for err. ErrorDetails(err error, details *ErrorDetails) }
ErrorDetailer defines an interface for altering or extending the ErrorDetails for an error.
ErrorDetailers can be registered using the package-level functions RegisterErrorDetailer and RegisterTypeErrorDetailer.
type ErrorDetailerFunc ¶ added in v1.3.0
type ErrorDetailerFunc func(error, *ErrorDetails)
ErrorDetailerFunc is a function type implementing ErrorDetailer.
func (ErrorDetailerFunc) ErrorDetails ¶ added in v1.3.0
func (f ErrorDetailerFunc) ErrorDetails(err error, details *ErrorDetails)
ErrorDetails calls f(err, details).
type ErrorDetails ¶ added in v1.3.0
type ErrorDetails struct { // Type holds information about the error type, initialized // with the type name and type package path using reflection. Type struct { // Name holds the error type name. Name string // PackagePath holds the error type package path. PackagePath string } // Code holds an error code. Code struct { // String holds a string-based error code. If this is set, then Number is ignored. // // This field will be initialized to the result of calling an error's Code method, // if the error implements the following interface: // // type interface StringCoder { // Code() string // } String string // Number holds a numerical error code. This is ignored if String is set. // // This field will be initialized to the result of calling an error's Code // method, if the error implements the following interface: // // type interface NumberCoder { // Code() float64 // } Number float64 } // Cause holds the errors that were the cause of this error. Cause []error // contains filtered or unexported fields }
ErrorDetails holds details of an error, which can be altered or extended by registering an ErrorDetailer with RegisterErrorDetailer or RegisterTypeErrorDetailer.
func (*ErrorDetails) SetAttr ¶ added in v1.3.0
func (d *ErrorDetails) SetAttr(k string, v interface{})
SetAttr sets the attribute with key k to value v.
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 // Error is an error associated with the log record. // // This is optional. Error error }
ErrorLogRecord holds details of an error log record.
type ExtendedSampler ¶ added in v1.9.0
type ExtendedSampler interface { // SampleExtended indicates whether or not a transaction // should be sampled, and the sampling rate in effect at // the time. This method will be invoked by calls to // Tracer.StartTransaction for the root of a trace, so it // must be goroutine-safe, and should avoid synchronization // as far as possible. SampleExtended(SampleParams) SampleResult }
ExtendedSampler may be implemented by Samplers, providing a method for sampling and returning an extended SampleResult.
TODO(axw) in v2.0.0, replace the Sampler interface with this.
type GatherMetricsFunc ¶ added in v1.0.0
GatherMetricsFunc is a function type implementing MetricsGatherer.
func (GatherMetricsFunc) GatherMetrics ¶ added in v1.0.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 MessageSpanContext ¶ added in v1.12.0
type MessageSpanContext struct { // QueueName holds the message queue name. QueueName string }
MessageSpanContext holds contextual information about a message.
type MetricLabel ¶ added in v1.0.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 v1.0.0
type Metrics struct {
// contains filtered or unexported fields
}
Metrics holds a set of metrics.
func (*Metrics) Add ¶ added in v1.0.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.
func (*Metrics) AddHistogram ¶ added in v1.15.0
func (m *Metrics) AddHistogram(name string, labels []MetricLabel, values []float64, counts []uint64)
AddHistogram adds a histogram metric with the given name, labels, counts, and values. The labels are expected to be sorted lexicographically, and bucket values provided in ascending order.
type MetricsGatherer ¶ added in v1.0.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 SampleParams ¶ added in v1.9.0
type SampleParams struct { // TraceContext holds the newly-generated TraceContext // for the root transaction which is being sampled. TraceContext TraceContext }
SampleParams holds parameters for SampleExtended.
type SampleResult ¶ added in v1.9.0
type SampleResult struct { // Sampled holds the sampling decision. Sampled bool // SampleRate holds the sample rate in effect at the // time of the sampling decision. This is used for // propagating the value downstream, and for inclusion // in events sent to APM Server. // // The sample rate will be rounded to 4 decimal places // half away from zero, except if it is in the interval // (0, 0.0001], in which case it is set to 0.0001. The // Sampler implementation should also internally apply // this logic to ensure consistency. SampleRate float64 }
SampleResult holds information about a sampling decision.
type Sampler ¶
type Sampler interface { // Sample indicates whether or not a transaction // should be sampled. This method will be invoked // by calls to Tracer.StartTransaction for the root // of a trace, so it must be goroutine-safe, and // should avoid synchronization as far as possible. Sample(TraceContext) bool }
Sampler provides a means of sampling transactions.
func NewRatioSampler ¶
NewRatioSampler returns a new Sampler with the given ratio
A ratio of 1.0 samples 100% of transactions, a ratio of 0.5 samples ~50%, and so on. If the ratio provided does not lie within the range [0,1.0], NewRatioSampler will panic.
Sampling rate is rounded to 4 digits half away from zero, except if it is in the interval (0, 0.0001], in which case is set to 0.0001.
The returned Sampler bases its decision on the value of the transaction ID, so there is no synchronization involved.
type Span ¶
type Span struct { // SpanData holds the span data. This field is set to nil when // the span's End method is called. *SpanData // contains filtered or unexported fields }
Span describes an operation within a transaction.
func SpanFromContext ¶
SpanFromContext returns the current Span in context, if any. The span must have been added to the context previously using ContextWithSpan, or the top-level StartSpan function.
func StartSpan ¶
StartSpan is equivalent to calling StartSpanOptions with a zero SpanOptions struct.
func StartSpanOptions ¶ added in v1.0.0
func StartSpanOptions(ctx context.Context, name, spanType string, opts SpanOptions) (*Span, context.Context)
StartSpanOptions 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.
If opts.Parent is non-zero, its value will be used in preference to any parent span in ctx.
StartSpanOptions always returns a non-nil Span. Its End method must be called when the span completes.
func (*Span) Dropped ¶
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 the span's start time.
func (*Span) IsExitSpan ¶ added in v1.14.0
IsExitSpan returns true if the span is an exit span.
func (*Span) ParentID ¶ added in v1.12.0
ParentID returns the ID of the span's parent span or transaction.
func (*Span) SetStacktrace ¶
SetStacktrace sets the stacktrace for the span, skipping the first skip number of frames, excluding the SetStacktrace function.
func (*Span) TraceContext ¶ added in v1.0.0
func (s *Span) TraceContext() TraceContext
TraceContext returns the span's TraceContext.
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) SetDatabaseRowsAffected ¶ added in v1.7.0
func (c *SpanContext) SetDatabaseRowsAffected(n int64)
SetDatabaseRowsAffected records the number of rows affected by a database operation.
func (*SpanContext) SetDestinationAddress ¶ added in v1.7.0
func (c *SpanContext) SetDestinationAddress(addr string, port int)
SetDestinationAddress sets the destination address and port in the context.
SetDestinationAddress has no effect when called with an empty addr.
func (*SpanContext) SetDestinationCloud ¶ added in v1.12.0
func (c *SpanContext) SetDestinationCloud(cloud DestinationCloudSpanContext)
SetDestinationCloud sets the destination cloud info in the context.
func (*SpanContext) SetDestinationService ¶ added in v1.7.0
func (c *SpanContext) SetDestinationService(service DestinationServiceSpanContext)
SetDestinationService sets the destination service info in the context.
Both service.Name and service.Resource are required. If either is empty, then SetDestinationService is a no-op.
func (*SpanContext) SetHTTPRequest ¶ added in v1.0.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.
SetHTTPRequest makes implicit calls to SetDestinationAddress and SetDestinationService, using details from req.URL.
func (*SpanContext) SetHTTPStatusCode ¶ added in v1.1.0
func (c *SpanContext) SetHTTPStatusCode(statusCode int)
SetHTTPStatusCode records the HTTP response status code.
If, when the transaction ends, its Outcome field has not been explicitly set, it will be set based on the status code: "success" if statusCode < 400, and "failure" otherwise.
func (*SpanContext) SetLabel ¶ added in v1.6.0
func (c *SpanContext) SetLabel(key string, value interface{})
SetLabel sets a label in the context.
Invalid characters ('.', '*', and '"') in the key will be replaced with underscores.
If the value is numerical or boolean, then it will be sent to the server as a JSON number or boolean; otherwise it will converted to a string, using `fmt.Sprint` if necessary. String values longer than 1024 characters will be truncated.
func (*SpanContext) SetMessage ¶ added in v1.12.0
func (c *SpanContext) SetMessage(message MessageSpanContext)
SetMessage sets the message info in the context.
message.Name is required. If it is empty, then SetMessage is a no-op.
func (*SpanContext) SetTag ¶ added in v1.0.0
func (c *SpanContext) SetTag(key, value string)
SetTag calls SetLabel(key, value).
SetTag is deprecated, and will be removed in a future major version.
type SpanData ¶ added in v1.1.0
type SpanData struct { // Name holds the span name, initialized with the value passed to StartSpan. Name string // Type holds the overarching span type, such as "db", and will be initialized // with the value passed to StartSpan. Type string // Subtype holds the span subtype, such as "mysql". This will initially be empty, // and can be set after starting the span. Subtype string // Action holds the span action, such as "query". This will initially be empty, // and can be set after starting the span. Action string // Duration holds the span duration, initialized to -1. // // If you do not update Duration, calling Span.End will calculate the // duration based on the elapsed time since the span's start time. Duration time.Duration // Outcome holds the span outcome: success, failure, or unknown (the default). // If Outcome is set to something else, it will be replaced with "unknown". // // Outcome is used for error rate calculations. A value of "success" indicates // that a operation succeeded, while "failure" indicates that the operation // failed. If Outcome is set to "unknown" (or some other value), then the // span will not be included in error rate calculations. Outcome string // Context describes the context in which span occurs. Context SpanContext // contains filtered or unexported fields }
SpanData holds the details for a span, and is embedded inside Span. When a span is ended or discarded, its SpanData field will be set to nil.
type SpanID ¶ added in v1.0.0
type SpanID [8]byte
SpanID identifies a span within a trace.
func (SpanID) MarshalText ¶ added in v1.1.0
MarshalText returns id encoded as hex, satisfying encoding.TextMarshaler.
type SpanOptions ¶ added in v1.0.0
type SpanOptions struct { // Parent, if non-zero, holds the trace context of the parent span. Parent TraceContext // SpanID holds the ID to assign to the span. If this is zero, a new ID // will be generated and used instead. SpanID SpanID // Indicates whether a span is an exit span or not. All child spans // will be noop spans. ExitSpan bool // Start is the start time of the span. If this has the zero value, // time.Now() will be used instead. // // When a span is created using Transaction.StartSpanOptions, the // span timestamp is internally calculated relative to the transaction // timestamp. // // When Tracer.StartSpan is used, this timestamp should be pre-calculated // as relative from the transaction start time, i.e. by calculating the // time elapsed since the transaction started, and adding that to the // transaction timestamp. Calculating the timstamp in this way will ensure // monotonicity of events within a transaction. Start time.Time // contains filtered or unexported fields }
SpanOptions holds options for Transaction.StartSpanOptions and Tracer.StartSpan.
type TraceContext ¶ added in v1.0.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 // State holds the trace state. State TraceState }
TraceContext holds trace context for an incoming or outgoing request.
type TraceID ¶ added in v1.0.0
type TraceID [16]byte
TraceID identifies a trace forest.
func (TraceID) MarshalText ¶ added in v1.1.0
MarshalText returns id encoded as hex, satisfying encoding.TextMarshaler.
type TraceOptions ¶ added in v1.0.0
type TraceOptions uint8
TraceOptions describes the options for a trace.
func (TraceOptions) Recorded ¶ added in v1.0.0
func (o TraceOptions) Recorded() bool
Recorded reports whether or not the transaction/span may have been (or may be) recorded.
func (TraceOptions) WithRecorded ¶ added in v1.0.0
func (o TraceOptions) WithRecorded(recorded bool) TraceOptions
WithRecorded changes the "recorded" flag, and returns the new options without modifying the original value.
type TraceState ¶ added in v1.7.0
type TraceState struct {
// contains filtered or unexported fields
}
TraceState holds vendor-specific state for a trace.
func NewTraceState ¶ added in v1.7.0
func NewTraceState(entries ...TraceStateEntry) TraceState
NewTraceState returns a TraceState based on entries.
func (TraceState) String ¶ added in v1.7.0
func (s TraceState) String() string
String returns s as a comma-separated list of key-value pairs.
func (TraceState) Validate ¶ added in v1.7.0
func (s TraceState) Validate() error
Validate validates the trace state.
This will return non-nil if any entries are invalid, if there are too many entries, or if an entry key is repeated.
type TraceStateEntry ¶ added in v1.7.0
type TraceStateEntry struct { // Key holds a vendor (and optionally, tenant) ID. Key string // Value holds a string representing trace state. Value string // contains filtered or unexported fields }
TraceStateEntry holds a trace state entry: a key/value pair representing state for a vendor.
func (*TraceStateEntry) Validate ¶ added in v1.7.0
func (e *TraceStateEntry) Validate() error
Validate validates the trace state entry.
This will return non-nil if either the key or value is invalid.
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
// Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Elasticsearch B.V. licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package main import ( "compress/zlib" "context" "encoding/json" "fmt" "io" "log" "net/http" "net/http/httptest" "os" "sync" "time" "go.elastic.co/apm" "go.elastic.co/apm/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 := apm.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 stream events to the APM server, and will // close the request when it reaches a given size in bytes // (ELASTIC_APM_API_REQUEST_SIZE) or a given duration has // elapsed (ELASTIC_APM_API_REQUEST_TIME). Even so, we flush // here to ensure the data reaches the server. tracer.Flush(nil) fmt.Println("number of payloads:", len(r.payloads)) metadata := r.payloads[0]["metadata"].(map[string]interface{}) service := metadata["service"].(map[string]interface{}) agent := service["agent"].(map[string]interface{}) language := service["language"].(map[string]interface{}) runtime := service["runtime"].(map[string]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"]) var transactions []map[string]interface{} var spans []map[string]interface{} for _, p := range r.payloads[1:] { t, ok := p["transaction"].(map[string]interface{}) if ok { transactions = append(transactions, t) continue } s, ok := p["span"].(map[string]interface{}) if ok { spans = append(spans, s) continue } } if len(transactions) != len(spans) { fmt.Printf("%d transaction(s), %d span(s)\n", len(transactions), len(spans)) return } for i, t := range transactions { s := spans[i] fmt.Printf(" transaction %d:\n", i) fmt.Println(" name:", t["name"]) fmt.Println(" type:", t["type"]) fmt.Println(" context:", t["context"]) fmt.Printf(" span %d:\n", i) fmt.Println(" name:", s["name"]) fmt.Println(" type:", s["type"]) } } type api struct { tracer *apm.Tracer } func (api *api) handleOrder(ctx context.Context, product string) { tx := api.tracer.StartTransaction("order", "request") defer tx.End() ctx = apm.ContextWithTransaction(ctx, tx) tx.Context.SetLabel("product", product) time.Sleep(10 * time.Millisecond) storeOrder(ctx, product) time.Sleep(20 * time.Millisecond) } func storeOrder(ctx context.Context, product string) { span, _ := apm.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) { if req.URL.Path != "/intake/v2/events" { // Ignore config requests. return } body, err := zlib.NewReader(req.Body) if err != nil { panic(err) } decoder := json.NewDecoder(body) var payloads []map[string]interface{} for { var m map[string]interface{} if err := decoder.Decode(&m); err != nil { if err == io.EOF { break } http.Error(w, err.Error(), http.StatusInternalServerError) return } payloads = append(payloads, m) } r.mu.Lock() r.payloads = append(r.payloads, payloads...) r.mu.Unlock() }
Output: number of payloads: 5 service name: service-name service version: 1.0.0 agent name: go language name: go runtime name: gc transaction 0: name: order type: request context: map[tags:map[product:fish fingers]] span 0: name: store_order type: rpc transaction 1: name: order type: request context: map[tags:map[product:detergent]] span 1: name: store_order 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 ¶
NewTracer returns a new Tracer, using the default transport, and with the specified service name and version if specified. This is equivalent to calling NewTracerOptions with a TracerOptions having ServiceName and ServiceVersion set to the provided arguments.
NOTE when this package is imported, DefaultTracer is initialised using environment variables for configuration. When creating a tracer with NewTracer or NewTracerOptions, you should close apm.DefaultTracer if it is not needed, e.g. by calling apm.DefaultTracer.Close() in an init function.
func NewTracerOptions ¶ added in v1.5.0
func NewTracerOptions(opts TracerOptions) (*Tracer, error)
NewTracerOptions returns a new Tracer using the provided options. See TracerOptions for details on the options, and their default values.
NOTE when this package is imported, DefaultTracer is initialised using environment variables for configuration. When creating a tracer with NewTracer or NewTracerOptions, you should close apm.DefaultTracer if it is not needed, e.g. by calling apm.DefaultTracer.Close() in an init function.
func (*Tracer) Active ¶
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. The BodyCapturer's Discard method should be called after it is no longer needed, in order to recycle its memory.
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) IgnoredTransactionURL ¶ added in v1.11.0
IgnoredTransactionURL returns whether the given transaction URL should be ignored
func (*Tracer) NewError ¶
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) Recording ¶ added in v1.8.0
Recording reports whether the tracer is recording events. Instrumentation may use this to avoid creating transactions, spans, and metrics when the tracer is configured to not record.
Recording will also return false if the tracer is inactive.
func (*Tracer) Recovered ¶
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.
func (*Tracer) RegisterMetricsGatherer ¶ added in v1.0.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 v1.0.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) SetCaptureHeaders ¶ added in v1.2.0
SetCaptureHeaders enables or disables capturing of HTTP headers.
func (*Tracer) SetConfigWatcher ¶ added in v1.5.0
SetConfigWatcher sets w as the config watcher.
By default, the tracer will be configured to use the transport for watching config, if the transport implements apmconfig.Watcher. This can be overridden by calling SetConfigWatcher.
If w is nil, config watching will be stopped.
Calling SetConfigWatcher will discard any previously observed remote config, reverting to local config until a config change from w is observed.
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) SetExitSpanMinDuration ¶ added in v1.15.0
SetExitSpanMinDuration sets the minimum duration for an exit span to not be dropped.
func (*Tracer) SetIgnoreTransactionURLs ¶ added in v1.11.0
SetIgnoreTransactionURLs sets the wildcard patterns that will be used to ignore transactions with matching URLs.
func (*Tracer) SetLogger ¶
SetLogger sets the Logger to be used for logging the operation of the tracer.
If logger implements WarningLogger, its Warningf method will be used for logging warnings. Otherwise, warnings will logged using Debugf.
The tracer is initialized with a default logger configured with the environment variables ELASTIC_APM_LOG_FILE and ELASTIC_APM_LOG_LEVEL. Calling SetLogger will replace the default logger.
func (*Tracer) SetMaxSpans ¶
SetMaxSpans sets the maximum number of spans that will be added to a transaction before dropping spans.
Passing in zero will disable all spans, while negative values will permit an unlimited number of spans.
func (*Tracer) SetMetricsInterval ¶ added in v1.0.0
SetMetricsInterval sets the metrics interval -- the amount of time in between metrics samples being gathered.
func (*Tracer) SetRecording ¶ added in v1.8.0
SetRecording enables or disables recording of future events.
SetRecording does not affect in-flight events.
func (*Tracer) SetRequestDuration ¶ added in v1.0.0
SetRequestDuration sets the maximum amount of time to keep a request open to the APM server for streaming data before closing the stream and starting a new request.
func (*Tracer) SetSampler ¶
SetSampler sets the sampler the tracer.
It is valid to pass nil, in which case all transactions will be sampled.
Configuration via Kibana takes precedence over local configuration, so if sampling has been configured via Kibana, this call will not have any effect until/unless that configuration has been removed.
func (*Tracer) SetSanitizedFieldNames ¶
SetSanitizedFieldNames sets the wildcard 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.
Configuration via Kibana takes precedence over local configuration, so if sanitized_field_names has been configured via Kibana, this call will not have any effect until/unless that configuration has been removed.
func (*Tracer) SetSpanCompressionEnabled ¶ added in v1.15.0
SetSpanCompressionEnabled enables/disables the span compression feature.
func (*Tracer) SetSpanCompressionExactMatchMaxDuration ¶ added in v1.15.0
SetSpanCompressionExactMatchMaxDuration sets the maximum duration for a span to be compressed with `compression_strategy` == `exact_match`.
func (*Tracer) SetSpanCompressionSameKindMaxDuration ¶ added in v1.15.0
SetSpanCompressionSameKindMaxDuration sets the maximum duration for a span to be compressed with `compression_strategy` == `same_kind`.
func (*Tracer) SetSpanFramesMinDuration ¶
SetSpanFramesMinDuration sets the minimum duration for a span after which we will capture its stack frames.
func (*Tracer) SetStackTraceLimit ¶ added in v1.4.0
SetStackTraceLimit sets the the maximum number of stack frames to collect for each stack trace. If limit is negative, then all frames will be collected.
func (*Tracer) ShouldPropagateLegacyHeader ¶ added in v1.8.0
ShouldPropagateLegacyHeader reports whether instrumentation should propagate the legacy "Elastic-Apm-Traceparent" header in addition to the standard W3C "traceparent" header.
This method will be removed in a future major version when we remove support for propagating the legacy header.
func (*Tracer) StartSpan ¶ added in v1.0.0
func (t *Tracer) StartSpan(name, spanType string, transactionID SpanID, opts SpanOptions) *Span
StartSpan returns a new Span with the specified name, type, transaction ID, and options. The parent transaction context and transaction IDs must have valid, non-zero values, or else the span will be dropped.
In most cases, you should use Transaction.StartSpan or Transaction.StartSpanOptions. This method is provided for corner-cases, such as starting a span after the containing transaction's End method has been called. Spans created in this way will not have the "max spans" configuration applied, nor will they be considered in any transaction's span count.
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 v1.0.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 TracerOptions ¶ added in v1.5.0
type TracerOptions struct { // ServiceName holds the service name. // // If ServiceName is empty, the service name will be defined using the // ELASTIC_APM_SERVICE_NAME environment variable, or if that is not set, // the executable name. ServiceName string // ServiceVersion holds the service version. // // If ServiceVersion is empty, the service version will be defined using // the ELASTIC_APM_SERVICE_VERSION environment variable. ServiceVersion string // ServiceEnvironment holds the service environment. // // If ServiceEnvironment is empty, the service environment will be defined // using the ELASTIC_APM_ENVIRONMENT environment variable. ServiceEnvironment string // Transport holds the transport to use for sending events. // // If Transport is nil, transport.Default will be used. // // If Transport implements apmconfig.Watcher, the tracer will begin watching // for remote changes immediately. This behaviour can be disabled by setting // the environment variable ELASTIC_APM_CENTRAL_CONFIG=false. Transport transport.Transport // contains filtered or unexported fields }
TracerOptions holds initial tracer options, for passing to NewTracerOptions.
type TracerStats ¶
type TracerStats struct { Errors TracerStatsErrors ErrorsSent uint64 ErrorsDropped uint64 TransactionsSent uint64 TransactionsDropped uint64 SpansSent uint64 SpansDropped uint64 }
TracerStats holds statistics for a Tracer.
type TracerStatsErrors ¶
TracerStatsErrors holds error statistics for a Tracer.
type Transaction ¶
type Transaction struct { // TransactionData holds the transaction data. This field is set to // nil when either of the transaction's End or Discard methods are called. *TransactionData // 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 ContextWithTransaction.
func (*Transaction) Discard ¶
func (tx *Transaction) Discard()
Discard discards a previously started transaction.
Calling Discard will set tx's TransactionData field to nil, so callers must ensure tx is not updated after Discard returns.
func (*Transaction) End ¶
func (tx *Transaction) End()
End enqueues tx for sending to the Elastic APM server.
Calling End will set tx's TransactionData field to nil, so callers must ensure tx is not updated after End returns.
If tx.Duration has not been set, End will set it to the elapsed time since the transaction's start time.
func (*Transaction) EnsureParent ¶ added in v1.0.0
func (tx *Transaction) EnsureParent() SpanID
EnsureParent returns the span ID for for tx's parent, generating a parent span ID if one has not already been set and tx has not been ended. If tx is nil or has been ended, a zero (invalid) SpanID is returned.
This method can be used for generating a span ID for the RUM (Real User Monitoring) agent, where the RUM agent is initialized after the backend service returns.
Example ¶
package main import ( "html/template" "os" "go.elastic.co/apm" ) func main() { tx := apm.DefaultTracer.StartTransactionOptions("name", "type", apm.TransactionOptions{ TraceContext: apm.TraceContext{ Trace: apm.TraceID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, Span: apm.SpanID{0, 1, 2, 3, 4, 5, 6, 7}, }, }) defer tx.Discard() tpl := template.Must(template.New("").Parse(` <script src="elastic-apm-js-base/dist/bundles/elastic-apm-js-base.umd.min.js"></script> <script> elasticApm.init({ serviceName: '', serverUrl: 'http://localhost:8200', pageLoadTraceId: {{.TraceContext.Trace}}, pageLoadSpanId: {{.EnsureParent}}, pageLoadSampled: {{.Sampled}}, }) </script> `)) if err := tpl.Execute(os.Stdout, tx); err != nil { panic(err) } }
Output: <script src="elastic-apm-js-base/dist/bundles/elastic-apm-js-base.umd.min.js"></script> <script> elasticApm.init({ serviceName: '', serverUrl: 'http://localhost:8200', pageLoadTraceId: "000102030405060708090a0b0c0d0e0f", pageLoadSpanId: "0001020304050607", pageLoadSampled: false , }) </script>
Example (NilTransaction) ¶
package main import ( "context" "html/template" "os" "go.elastic.co/apm" ) func main() { tpl := template.Must(template.New("").Parse(` <script> elasticApm.init({ {{.TraceContext.Trace}}, {{.EnsureParent}}, {{.Sampled}}, }) </script> `)) // Demonstrate that Transaction's TraceContext, EnsureParent, // and Sampled methods will not panic when called with a nil // Transaction. tx := apm.TransactionFromContext(context.Background()) if err := tpl.Execute(os.Stdout, tx); err != nil { panic(err) } }
Output: <script> elasticApm.init({ "00000000000000000000000000000000", "0000000000000000", false , }) </script>
func (*Transaction) ParentID ¶ added in v1.12.0
func (tx *Transaction) ParentID() SpanID
ParentID returns the ID of the transaction's Parent or a zero (invalid) SpanID.
func (*Transaction) Sampled ¶
func (tx *Transaction) Sampled() bool
Sampled reports whether or not the transaction is sampled.
func (*Transaction) ShouldPropagateLegacyHeader ¶ added in v1.6.0
func (tx *Transaction) ShouldPropagateLegacyHeader() bool
ShouldPropagateLegacyHeader reports whether instrumentation should propagate the legacy "Elastic-Apm-Traceparent" header in addition to the standard W3C "traceparent" header.
This method will be removed in a future major version when we remove support for propagating the legacy header.
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.
StartSpan always returns a non-nil Span, with a non-nil SpanData field. Its End method must be called when the span completes.
If the span type contains two dots, they are assumed to separate the span type, subtype, and action; a single dot separates span type and subtype, and the action will not be set.
StartSpan is equivalent to calling StartSpanOptions with SpanOptions.Parent set to the trace context of parent if parent is non-nil.
func (*Transaction) StartSpanOptions ¶ added in v1.0.0
func (tx *Transaction) StartSpanOptions(name, spanType string, opts SpanOptions) *Span
StartSpanOptions starts and returns a new Span within the transaction, with the specified name, type, and options.
StartSpan always returns a non-nil Span. Its End method must be called when the span completes.
If the span type contains two dots, they are assumed to separate the span type, subtype, and action; a single dot separates span type and subtype, and the action will not be set.
func (*Transaction) TraceContext ¶ added in v1.0.0
func (tx *Transaction) TraceContext() TraceContext
TraceContext returns the transaction's TraceContext.
The resulting TraceContext's Span field holds the transaction's ID. If tx is nil, a zero (invalid) TraceContext is returned.
type TransactionData ¶ added in v1.1.0
type TransactionData struct { // Name holds the transaction name, initialized with the value // passed to StartTransaction. Name string // Type holds the transaction type, initialized with the value // passed to StartTransaction. Type string // Duration holds the transaction duration, initialized to -1. // // If you do not update Duration, calling Transaction.End will // calculate the duration based on the elapsed time since the // transaction's start time. Duration time.Duration // Context describes the context in which the transaction occurs. Context Context // Result holds the transaction result. Result string // Outcome holds the transaction outcome: success, failure, or // unknown (the default). If Outcome is set to something else, // it will be replaced with "unknown". // // Outcome is used for error rate calculations. A value of "success" // indicates that a transaction succeeded, while "failure" indicates // that the transaction failed. If Outcome is set to "unknown" (or // some other value), then the transaction will not be included in // error rate calculations. Outcome string // contains filtered or unexported fields }
TransactionData holds the details for a transaction, and is embedded inside Transaction. When a transaction is ended, its TransactionData field will be set to nil.
type TransactionOptions ¶ added in v1.0.0
type TransactionOptions struct { // TraceContext holds the TraceContext for a new transaction. If this is // zero, a new trace will be started. TraceContext TraceContext // TransactionID holds the ID to assign to the transaction. If this is // zero, a new ID will be generated and used instead. TransactionID SpanID // 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.
type WarningLogger ¶ added in v1.5.0
type WarningLogger interface { Logger // Warningf logs a message at warning level. Warningf(format string, args ...interface{}) }
WarningLogger extends Logger with a Warningf method.
TODO(axw) this will be removed in v2.0.0, and the Warningf method will be added directly to Logger.
Source Files ¶
- breakdown.go
- builtin_metrics.go
- capturebody.go
- config.go
- context.go
- doc.go
- error.go
- error_unix.go
- fmt.go
- fnv.go
- gocontext.go
- logger.go
- metrics.go
- modelwriter.go
- profiling.go
- sampler.go
- sanitizer.go
- span.go
- span_compressed.go
- spancontext.go
- stacktrace.go
- tracecontext.go
- tracer.go
- tracer_stats.go
- transaction.go
- utils.go
- utils_linux.go
- version.go
Directories ¶
Path | Synopsis |
---|---|
Package apmconfig provides an API for watching agent config changes.
|
Package apmconfig provides an API for watching agent config changes. |
internal
|
|
iochan
Package iochan provides a channel-based io.Reader.
|
Package iochan provides a channel-based io.Reader. |
ringbuffer
Package ringbuffer provides a ring buffer for storing blocks of bytes.
|
Package ringbuffer provides a ring buffer for storing blocks of bytes. |
sqlutil
Package sqlutil provides utilities to SQL-related instrumentation modules.
|
Package sqlutil provides utilities to SQL-related instrumentation modules. |
wildcard
Package wildcard provides a fast, zero-allocation wildcard matcher.
|
Package wildcard provides a fast, zero-allocation wildcard matcher. |
Package model provides the Elastic APM model types.
|
Package model provides the Elastic APM model types. |
module
|
|
apmawssdkgo
Module
|
|
apmazure
Module
|
|
apmbeego
Module
|
|
apmchi
Module
|
|
apmchiv5
Module
|
|
apmecho
Module
|
|
apmechov4
Module
|
|
apmelasticsearch
Module
|
|
apmfasthttp
Module
|
|
apmfiber
Module
|
|
apmgin
Module
|
|
apmgocql
Module
|
|
apmgokit
Module
|
|
apmgometrics
Module
|
|
apmgopg
Module
|
|
apmgopgv10
Module
|
|
apmgoredis
Module
|
|
apmgoredisv8
Module
|
|
apmgorilla
Module
|
|
apmgorm
Module
|
|
apmgormv2
Module
|
|
apmgrpc
Module
|
|
apmhttp
Module
|
|
apmhttprouter
Module
|
|
apmlambda
Module
|
|
apmlogrus
Module
|
|
apmmongo
Module
|
|
apmnegroni
Module
|
|
apmot
Module
|
|
apmotel
Module
|
|
apmpgx
Module
|
|
apmpgxv5
Module
|
|
apmprometheus
Module
|
|
apmredigo
Module
|
|
apmrestful
Module
|
|
apmrestfulv3
Module
|
|
apmsql
Module
|
|
apmzap
Module
|
|
apmzerolog
Module
|
|
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. |