ao

package
v0.0.0-...-e098d20 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2022 License: Apache-2.0 Imports: 21 Imported by: 5

Documentation

Overview

Package ao implements a simple API for distributed tracing using AppOptics.

For more details and usage examples, please visit https://github.com/45638654564654/appoptics-apm-go#readme and https://docs.appoptics.com/kb/apm_tracing/custom_instrumentation/

Index

Examples

Constants

View Source
const (
	// HTTPHeaderName is a constant for the HTTP header used by AppOptics ("X-Trace") to propagate
	// the distributed tracing context across HTTP requests.
	HTTPHeaderName = "X-Trace"
	// HTTPHeaderXTraceOptions is a constant for the HTTP header to propagate X-Trace-Options
	// values. It's for trigger trace requests and may be used for other purposes in the future.
	HTTPHeaderXTraceOptions = reporter.HTTPHeaderXTraceOptions
	// HTTPHeaderXTraceOptionsSignature is a constant for the HTTP headers to propagate
	// X-Trace-Options-Signature values. It contains the response codes for X-Trace-Options
	HTTPHeaderXTraceOptionsSignature = reporter.HTTPHeaderXTraceOptionsSignature
)
View Source
const (
	// KeyBackTrace is the key to report current stack trace.
	KeyBackTrace = "Backtrace"
)

The keys to be used in reporting events

View Source
const (
	// LoggableTraceID is used as the key for log injection.
	LoggableTraceID = "ao.traceId"
)
View Source
const (
	// MaxCustomTransactionNameLength defines the maximum length of a user-provided
	// transaction name.
	MaxCustomTransactionNameLength = 255
)
View Source
const (
	// MaxTagsCount is the maximum number of tags allowed.
	MaxTagsCount = metrics.MaxTagsCount
)

Variables

View Source
var (
	// ErrExceedsTagsCountLimit indicates the count of tags exceeds the limit
	ErrExceedsTagsCountLimit = metrics.ErrExceedsTagsCountLimit
	// ErrExceedsMetricsCountLimit indicates there are too many distinct measurements in a flush cycle.
	ErrExceedsMetricsCountLimit = metrics.ErrExceedsMetricsCountLimit
	// ErrMetricsWithNonPositiveCount indicates the count is negative or zero
	ErrMetricsWithNonPositiveCount = metrics.ErrMetricsWithNonPositiveCount
)

The measurements submission errors

Functions

func Closed

func Closed() bool

Closed denotes if the agent is closed (by either calling Shutdown explicitly or being triggered from some internal error).

func End

func End(ctx context.Context, args ...interface{})

End ends a Span, given a context ctx that was associated with it, optionally reporting KV pairs provided by args.

func EndTrace

func EndTrace(ctx context.Context)

EndTrace ends a Trace, given a context that was associated with the trace.

func Err

func Err(ctx context.Context, err error)

Err reports details error err (along with a stack trace) on the Span associated with the context ctx.

func Error

func Error(ctx context.Context, class, msg string)

Error reports details about an error (along with a stack trace) on the Span associated with the context ctx.

func FromXTraceIDContext

func FromXTraceIDContext(ctx context.Context, xTraceID string) context.Context

func GetLogLevel

func GetLogLevel() string

GetLogLevel returns the current logging level of the AppOptics agent

func GetTransactionName

func GetTransactionName(ctx context.Context) string

GetTransactionName fetches the current transaction name from the context

func HTTPHandler

func HTTPHandler(handler func(http.ResponseWriter, *http.Request), opts ...SpanOpt) func(http.ResponseWriter, *http.Request)

HTTPHandler wraps an http.HandlerFunc with entry / exit events, returning a new handler that can be used in its place.

http.HandleFunc("/path", ao.HTTPHandler(myHandler))

func IncrementMetric

func IncrementMetric(name string, opts MetricOptions) error

IncrementMetric submits a incremental measurement to the reporter. The measurements will be collected in the background and reported periodically.

func Info

func Info(ctx context.Context, args ...interface{})

Info reports KV pairs provided by args for the Span associated with the context ctx.

func IsSampled

func IsSampled(ctx context.Context) bool

IsSampled returns whether or not the Layer span's context is sampled

func LogRequestMiddleware

func LogRequestMiddleware(next fasthttp.RequestHandler, opts ...SpanOpt) fasthttp.RequestHandler

func MetadataString

func MetadataString(ctx context.Context) string

MetadataString returns a representation of the Span's context for use with distributed tracing (to create a remote child span). If the Span has ended, an empty string is returned.

func NewContext

func NewContext(ctx context.Context, t Trace) context.Context

NewContext returns a copy of the parent context and associates it with a Trace.

func SetLogLevel

func SetLogLevel(level string) error

SetLogLevel changes the logging level of the AppOptics agent Valid logging levels: DEBUG, INFO, WARN, ERROR

func SetLogOutput

func SetLogOutput(w io.Writer)

SetLogOutput sets the output destination for the internal logger.

func SetServiceKey

func SetServiceKey(key string)

SetServiceKey sets the service key of the agent

func SetTransactionName

func SetTransactionName(ctx context.Context, name string) error

SetTransactionName can be called inside a http handler to set the custom transaction name.

func Shutdown

func Shutdown(ctx context.Context) error

Shutdown flush the metrics and stops the agent. The call will block until the agent flushes and is successfully shutdown or the context is canceled. It returns nil for successful shutdown and or error when the context is canceled or the agent has already been closed before.

This function should be called only once.

func SummaryMetric

func SummaryMetric(name string, value float64, opts MetricOptions) error

SummaryMetric submits a summary type measurement to the reporter. The measurements will be collected in the background and reported periodically.

func WaitForReady

func WaitForReady(ctx context.Context) bool

WaitForReady checks if the agent is ready. It returns true is the agent is ready, or false if it is not.

A call to this method will block until the agent is ready or the context is canceled, or the agent is already closed. The agent is considered ready if there is a valid default setting for sampling.

Types

type ContextOptions

type ContextOptions = reporter.ContextOptions

ContextOptions is an alias of the reporter's ContextOptions

type Exporter

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

func NewExporter

func NewExporter(shutdownDelay int) *Exporter

NewExporter creates an instance of the Solarwinds AppOptics exporter for OTEL traces.

func (*Exporter) ExportSpans

func (e *Exporter) ExportSpans(ctx context.Context, spans []sdktrace.ReadOnlySpan) error

func (*Exporter) Shutdown

func (e *Exporter) Shutdown(ctx context.Context) error

type FastHTTPResponseWriter

type FastHTTPResponseWriter struct {
	Writer *fasthttp.RequestCtx

	StatusCode  int
	WroteHeader bool
	// contains filtered or unexported fields
}

HTTPResponseWriter observes an http.ResponseWriter when WriteHeader() or Write() is called to check the status code and response headers.

type HTTPClientSpan

type HTTPClientSpan struct{ Span }

HTTPClientSpan is a Span that aids in reporting HTTP client requests.

req, err := http.NewRequest("GET", "http://example.com", nil)
l := ao.BeginHTTPClientSpan(ctx, httpReq)
defer l.End()
// ...
resp, err := client.Do(req)
l.AddHTTPResponse(resp, err)
// ...

func BeginHTTPClientSpan

func BeginHTTPClientSpan(ctx context.Context, req *http.Request) HTTPClientSpan

BeginHTTPClientSpan stores trace metadata in the headers of an HTTP client request, allowing the trace to be continued on the other end. It returns a Span that must have End() called to benchmark the client request, and should have AddHTTPResponse(r, err) called to process response metadata.

func (HTTPClientSpan) AddHTTPResponse

func (l HTTPClientSpan) AddHTTPResponse(resp *http.Response, err error)

AddHTTPResponse adds information from http.Response to this span. It will also check the HTTP response headers and propagate any valid distributed trace context from the end of the HTTP server's span to this one.

type HTTPResponseWriter

type HTTPResponseWriter struct {
	Writer http.ResponseWriter

	StatusCode  int
	WroteHeader bool
	// contains filtered or unexported fields
}

HTTPResponseWriter observes an http.ResponseWriter when WriteHeader() or Write() is called to check the status code and response headers.

func (*HTTPResponseWriter) Header

func (w *HTTPResponseWriter) Header() http.Header

Header implements the http.ResponseWriter interface.

func (*HTTPResponseWriter) Write

func (w *HTTPResponseWriter) Write(p []byte) (n int, err error)

func (*HTTPResponseWriter) WriteHeader

func (w *HTTPResponseWriter) WriteHeader(status int)

WriteHeader implements the http.ResponseWriter interface.

type KVMap

type KVMap = reporter.KVMap

KVMap is a map of additional key-value pairs to report along with the event data provided to AppOptics. Certain key names (such as "Query" or "RemoteHost") are used by AppOptics to provide details about program activity and distinguish between different types of spans. Please visit https://docs.appoptics.com/kb/apm_tracing/custom_instrumentation/ for details on the key names that AppOptics looks for.

type MetricOptions

type MetricOptions = metrics.MetricOptions

MetricOptions is a struct for the optional parameters of a measurement.

type Overrides

type Overrides struct {
	ExplicitTS    time.Time
	ExplicitMdStr string
}

type Profile deprecated

type Profile interface {
	// End ends a Profile, optionally reporting KV pairs provided by args.
	End(args ...interface{})
	// Error reports details about an error (along with a stack trace) for this Profile.
	Error(class, msg string)
	// Err reports details about error err (along with a stack trace) for this Profile.
	Err(error)
}

Profile is used to provide micro-benchmarks of named timings inside a Span.

Deprecated: Profile exists for historical compatibility and should not be used, use Span instead.

func BeginProfile deprecated

func BeginProfile(ctx context.Context, profileName string, args ...interface{}) Profile

BeginProfile begins a profiled block or method and return a context that should be closed with End(). You can use defer to profile a function in one line, as below:

func exampleFunc(ctx context.Context) {
    defer ao.BeginProfile(ctx, "exampleFunc").End()
    // ... do something ...
 }

Deprecated: BeginProfile exists for historical compatibility and should not be used, use BeginSpan instead.

type Span

type Span interface {
	// BeginSpan starts a new Span, returning a child of this Span.
	BeginSpan(spanName string, args ...interface{}) Span

	// BeginSpanWithOptions starts a new child span with provided options
	BeginSpanWithOptions(spanName string, opts SpanOptions, args ...interface{}) Span

	BeginSpanWithOverrides(spanName string, opts SpanOptions, overrides Overrides, args ...interface{}) Span

	// BeginProfile starts a new Profile, used to measure a named span
	// of time spent in this Span.
	//
	// Deprecated: BeginProfile exists for historical compatibility and should not be
	// used, use BeginSpan instead.
	BeginProfile(profileName string, args ...interface{}) Profile
	// End ends a Span, optionally reporting KV pairs provided by args.
	End(args ...interface{})

	EndWithOverrides(overrides Overrides, args ...interface{})

	// AddEndArgs adds additional KV pairs that will be serialized (and
	// dereferenced, for pointer values) at the end of this trace's span.
	AddEndArgs(args ...interface{})

	// Info reports KV pairs provided by args for this Span.
	Info(args ...interface{})

	// InfoWithOptions reports a new info event with the KVs and options provided
	InfoWithOptions(opts SpanOptions, args ...interface{})

	// InfoWithOverrides reports a new info event with the KVs, options and overrides
	InfoWithOverrides(overrides Overrides, opts SpanOptions, args ...interface{})

	// Error reports details about an error (along with a stack trace) for this Span.
	Error(class, msg string)
	// Err reports details about error err (along with a stack trace) for this Span.
	Err(error)

	// MetadataString returns a string representing this Span for use
	// in distributed tracing, e.g. to provide as an "X-Trace" header
	// in an outgoing HTTP request.
	MetadataString() string

	// IsSampled returns whether or not this Layer is sampled
	IsSampled() bool

	// SetAsync(true) provides a hint that this Span is a parent of
	// concurrent overlapping child Spans.
	SetAsync(bool)

	// SetOperationName sets or changes the span's operation name
	SetOperationName(string)

	// SetTransactionName sets this service's transaction name.
	// It is used for categorizing service metrics and traces in AppOptics.
	SetTransactionName(string) error

	// GetTransactionName returns the current value of the transaction name
	GetTransactionName() string

	IsReporting() bool
	// contains filtered or unexported methods
}

Span is used to measure a span of time associated with an activity such as an RPC call, DB query, or method invocation.

func BeginCacheSpan

func BeginCacheSpan(ctx context.Context, spanName, op, key, remoteHost string, hit bool, args ...interface{}) Span

BeginCacheSpan returns a Span that reports metadata used by AppOptics to filter cache/KV server request latency heatmaps and charts by span name, cache operation and hostname. Required parameter "op" is meant to report a Redis or Memcached command e.g. "HGET" or "set". Filterable hit/miss ratios charts will be available if "hit" is used. Optional parameter "key" will display in the trace's details, but will not be indexed. Call or defer the returned Span's End() to time the request's client-side latency.

func BeginQuerySpan

func BeginQuerySpan(ctx context.Context, spanName, query, flavor, remoteHost string, args ...interface{}) Span

BeginQuerySpan returns a Span that reports metadata used by AppOptics to filter query latency heatmaps and charts by span name, query statement, DB host and table. Parameter "flavor" specifies the flavor of the query statement, such as "mysql", "postgresql", or "mongodb". Call or defer the returned Span's End() to time the query's client-side latency.

func BeginRPCSpan

func BeginRPCSpan(ctx context.Context, spanName, protocol, controller, remoteHost string,
	args ...interface{}) Span

BeginRPCSpan returns a Span that reports metadata used by AppOptics to filter RPC call latency heatmaps and charts by span name, protocol, controller, and remote host. Call or defer the returned Span's End() to time the call's client-side latency.

func BeginRemoteURLSpan

func BeginRemoteURLSpan(ctx context.Context, spanName, remoteURL string, args ...interface{}) Span

BeginRemoteURLSpan returns a Span that reports metadata used by AppOptics to filter RPC call latency heatmaps and charts by span name and URL endpoint. For requests using the "net/http" package, BeginHTTPClientSpan also reports this metadata, while also propagating trace context metadata headers via http.Request and http.Response. Call or defer the returned Span's End() to time the call's client-side latency.

func BeginSpan

func BeginSpan(ctx context.Context, spanName string, args ...interface{}) (Span, context.Context)

BeginSpan starts a new Span, provided a parent context and name. It returns a Span and context bound to the new child Span.

Example
package main

import (
	"context"

	"github.com/45638654564654/appoptics-apm-go/v1/ao"
)

func main() {
	// create trace and bind to context, reporting first event
	ctx := ao.NewContext(context.Background(), ao.NewTrace("baseSpan"))
	// ... do something ...

	// instrument a DB query
	l, _ := ao.BeginSpan(ctx, "DBx", "Query", "SELECT * FROM tbl")
	// .. execute query ..
	l.End()

	// end trace
	ao.EndTrace(ctx)
}
Output:

func BeginSpanWithOptions

func BeginSpanWithOptions(ctx context.Context, spanName string, opts SpanOptions, args ...interface{}) (Span, context.Context)

BeginSpanWithOptions starts a span with provided options

func BeginSpanWithOverrides

func BeginSpanWithOverrides(ctx context.Context, spanName string, opts SpanOptions, overrides Overrides, args ...interface{}) (Span, context.Context)

func FromContext

func FromContext(ctx context.Context) Span

FromContext returns the Span bound to the context, if any.

type SpanOpt

type SpanOpt func(*SpanOptions)

SpanOpt defines the function type that changes the SpanOptions

func WithBackTrace

func WithBackTrace() SpanOpt

WithBackTrace returns a function that sets the WithBackTrace flag

type SpanOptions

type SpanOptions struct {
	// WithBackTrace indicates whether to include the backtrace in BeginSpan
	// Keep in mind that the cost of this option may be high as it calls
	// `debug.Stack()` internally to gather the stack trace. Please consider
	// the impact on performance/memory footprint carefully.
	WithBackTrace bool

	ContextOptions
	TransactionName string
}

SpanOptions defines the options of creating a span

type Trace

type Trace interface {
	// Span inherited from the Span interface
	// BeginSpan(spanName string, args ...interface{}) Span
	// End(args ...interface{})
	// Info(args ...interface{})
	// Error(class, msg string)
	// Err(error)
	// IsSampled() bool
	Span

	// EndCallback ends a trace, and include KV pairs returned by func f.
	// Useful alternative to End() when used with defer to delay evaluation
	// of KVs until the end of the trace (since a deferred function's
	// arguments are evaluated when the defer statement is
	// evaluated). Func f will not be called at all if this span is
	// not tracing.
	EndCallback(f func() KVMap)

	// ExitMetadata returns a hex string that propagates the end of
	// this span back to a remote client. It is typically used in an
	// response header (e.g. the HTTP Header "X-Trace"). Call this
	// method to set a response header in advance of calling End().
	ExitMetadata() string

	// SetMethod sets the request's HTTP method of the trace, if any.
	// It is used for categorizing service metrics and traces in AppOptics.
	SetMethod(method string)

	// SetPath extracts the full Path from http.Request
	SetPath(url string)

	// SetHost extracts the host information from http.Request
	SetHost(host string)

	// SetStatus sets the request's HTTP status code of the trace, if any.
	// It is used for categorizing service metrics and traces in AppOptics.
	SetStatus(status int)

	// SetStartTime sets the start time of a span.
	SetStartTime(start time.Time)

	// LoggableTraceID returns the trace ID for log injection.
	LoggableTraceID() string

	// HTTPRspHeaders returns the headers for HTTP response
	HTTPRspHeaders() map[string]string

	// SetHTTPRspHeaders attach the headers to a trace
	SetHTTPRspHeaders(map[string]string)
}

Trace represents the root span of a distributed trace for this request that reports events to AppOptics. The Trace interface extends the Span interface with additional methods that can be used to help categorize a service's inbound requests on the AppOptics service dashboard.

func ApmTraceFromHTTPRequestResponse

func ApmTraceFromHTTPRequestResponse(spanName string, ctx *fasthttp.RequestCtx, opts ...SpanOpt) (Trace, *fasthttp.RequestCtx)

func NewNullTrace

func NewNullTrace() Trace

NewNullTrace returns a trace that is not sampled.

func NewTrace

func NewTrace(spanName string) Trace

NewTrace creates a new Trace for reporting to AppOptics and immediately records the beginning of a root span named spanName. If this trace is sampled, it may report event data to AppOptics; otherwise event reporting will be a no-op.

Example
package main

import (
	"context"

	"github.com/45638654564654/appoptics-apm-go/v1/ao"
)

func main() {
	f0 := func(ctx context.Context) { // example span
		l, _ := ao.BeginSpan(ctx, "myDB",
			"Query", "SELECT * FROM tbl1",
			"RemoteHost", "db1.com")
		// ... run a query ...
		l.End()
	}

	// create a new trace, and a context to carry it around
	ctx := ao.NewContext(context.Background(), ao.NewTrace("myExample"))
	// do some work
	f0(ctx)
	// end the trace
	ao.EndTrace(ctx)
}
Output:

func NewTraceFromID

func NewTraceFromID(spanName, mdStr string, cb func() KVMap) Trace

NewTraceFromID creates a new Trace for reporting to AppOptics, provided an incoming trace ID (e.g. from a incoming RPC or service call's "X-Trace" header). If callback is provided & trace is sampled, cb will be called for entry event KVs

func NewTraceFromIDForURL

func NewTraceFromIDForURL(spanName, mdStr string, url string, cb func() KVMap) Trace

NewTraceFromIDForURL creates a new Trace for the provided URL to report to AppOptics, provided an incoming trace ID (e.g. from a incoming RPC or service call's "X-Trace" header). If callback is provided & trace is sampled, cb will be called for entry event KVs

func NewTraceFromIDForURLWithOverrides

func NewTraceFromIDForURLWithOverrides(spanName, mdStr string, url string, overrides Overrides, cb func() KVMap) Trace

NewTraceFromIDForURLWithOverrides creates a new Trace for the provided URL to report to AppOptics, provided an incoming trace ID (e.g. from a incoming RPC or service call's "X-Trace" header). Adds ability to provide overrides. If callback is provided & trace is sampled, cb will be called for entry event KVs

func NewTraceWithOptions

func NewTraceWithOptions(spanName string, opts SpanOptions) Trace

NewTraceWithOptions creates a new trace with the provided options

func NewTraceWithOverrides

func NewTraceWithOverrides(spanName string, overrides Overrides, cb func() KVMap) Trace

func TraceFromContext

func TraceFromContext(ctx context.Context) Trace

TraceFromContext returns the Trace bound to the context, if any.

func TraceFromHTTPRequestResponse

func TraceFromHTTPRequestResponse(spanName string, w http.ResponseWriter, r *http.Request, opts ...SpanOpt) (Trace, http.ResponseWriter,
	*http.Request)

TraceFromHTTPRequestResponse returns a Trace, a wrapped http.ResponseWriter, and a modified http.Request, given a http.ResponseWriter and http.Request. If a distributed trace is described in the HTTP request headers, the trace's context will be continued. The returned http.ResponseWriter should be used in place of the one passed into this function in order to observe the response's headers and status code.

func myHandler(w http.ResponseWriter, r *http.Request) {
    tr, w, r := ao.TraceFromHTTPRequestResponse("myHandler", w, r)
    defer tr.End()
    // ...
}

Directories

Path Synopsis
internal
config
Package config is responsible for loading the configuration from various sources, e.g., environment variables, configuration files and user input.
Package config is responsible for loading the configuration from various sources, e.g., environment variables, configuration files and user input.
graphtest
Package graphtest provides test utilities for asserting properties of event graphs.
Package graphtest provides test utilities for asserting properties of event graphs.
host
Package host has all the functions to get host metadata needed by traces and metrics.
Package host has all the functions to get host metadata needed by traces and metrics.
log
Package log implements a leveled logging system.
Package log implements a leveled logging system.
reporter
Package reporter provides a low-level API for creating and reporting events for distributed tracing with AppOptics.
Package reporter provides a low-level API for creating and reporting events for distributed tracing with AppOptics.

Jump to

Keyboard shortcuts

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