Documentation
ΒΆ
Overview ΒΆ
Package gotell extends the OpenTelemetry SDK with helpful utilities and sane defaults.
Index ΒΆ
- Constants
- Variables
- func ContextLabeler(ctx context.Context) (context.Context, *otelhttp.Labeler)
- func FilterHeaders(headers http.Header, includedKeys ...string) http.Header
- func ForceFlush(ctx context.Context) error
- func FunctionAttributes(skip int) []attribute.KeyValue
- func FunctionInfoAttributes(info *FunctionInfo) []attribute.KeyValue
- func Initialize(ctx context.Context, res *resource.Resource, options ...Option) error
- func Logger() log.Logger
- func Logr(ctx context.Context) logr.Logger
- func Meter() metric.Meter
- func OpenSQL(driverName, dataSourceName string) (*sql.DB, error)
- func RequestAttributes(req *http.Request) []attribute.KeyValue
- func ResponseWriterAttributes(w http.ResponseWriter) []attribute.KeyValue
- func Shutdown(ctx context.Context) error
- func Slog() *slog.Logger
- func SpanNameFormatter(operation string, req *http.Request) string
- func Tracer(ctx context.Context) trace.Tracer
- func WithInstrumentationMiddleware(next http.Handler) http.Handler
- func WithMetrics(next http.RoundTripper) http.RoundTripper
- type Counter
- type ForceFlusher
- type FunctionInfo
- type Histogram
- type MetricHandlerFn
- type MiddlewareFn
- type MiddlewareWrapperFn
- type Number
- type Option
- type OptionFn
- type Options
- type ResponseContentLengthReporter
- type ResponseStatusReporter
- type ResponseWriter
- type RoundTripperFn
- type Shutdowner
- type Span
- type StatusText
Constants ΒΆ
const ( // NAME contains the package name. It's used to separate all OpenTelemetry // instances from the upstream. NAME = "github.com/wwmoraes/gotell" )
Variables ΒΆ
var ( // NewGRPCServerHandler creates a stats.Handler for a gRPC server. NewGRPCServerHandler = otelgrpc.NewServerHandler // NewGRPCClientHandler creates a stats.Handler for a gRPC client. NewGRPCClientHandler = otelgrpc.NewClientHandler )
var ErrForceFlush = errors.New("failed to force flush provider")
ErrForceFlush happens when a provider fails to force flush
var ErrShutdownFailed = errors.New("failed to shutdown provider")
ErrShutdownFailed happens when a provider fails to shutdown
Functions ΒΆ
func ContextLabeler ΒΆ
ContextLabeler is an idempotent way to retrieve a labeler from a context.
It'll return the existing labeler or set an empty labeler if none is present.
func FilterHeaders ΒΆ
FilterHeaders returns a subset of headers for the given keys. The values are not copies.
func ForceFlush ΒΆ
ForceFlush flushes the default logger, metric and tracer providers. Each will run on a separate goroutine. It'll return the first error if any happens and cancel the other routines.
It works on any provider that implements the ForceFlusher interface. The OTEL standard providers do, for instance. It'll ignore providers that don't.
func FunctionAttributes ΒΆ
FunctionAttributes is a convenience function that runs GetFunctionInfo then FunctionInfoAttributes.
Skip equals zero means the caller of this function.
func FunctionInfoAttributes ΒΆ
func FunctionInfoAttributes(info *FunctionInfo) []attribute.KeyValue
FunctionInfoAttributes converts the information from FunctionInfo into OpenTelemetry semantic attributes.
func Initialize ΒΆ
Initialize sets up OpenTelemetry log, metric and trace providers. It provides sane and configurable defaults. Those use upstream SDK environment variables as much as possible.
This function is re-entrant but not idempotent: multiple calls yields new pointers for defaults. This is rarely what you want. It covers the use-case of an application initiatizing instrumentation in the main body as early as possible.
As for the SDK environment variables, there's a few caveats:
- use both W3C Trace Context and W3C Baggage (OTEL_PROPAGATORS isn't supported by the Golang SDK)
- uses OTLP exporters over gRPC (ignores OTEL_LOGS_EXPORTER, OTEL_METRICS_EXPORTER and OTEL_TRACES_EXPORTER)
- uses batch processors for spans and logs
- uses a periodic reader processor for metrics
See https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/
func Logr ΒΆ
Logr creates an instrumented logr.Logger for the target context.
It uses the existing logr from the context by combining the original sink and an OpenTelemetry sink. This allows the caller to configure defaults through the standard logr.NewContext.
It'll return a standard logr.Logger with an OpenTelemetry sink if there's no default set.
func RequestAttributes ΒΆ
RequestAttributes populates
func ResponseWriterAttributes ΒΆ
func ResponseWriterAttributes(w http.ResponseWriter) []attribute.KeyValue
ResponseWriterAttributes derives observability attributes from a response writer.
It checks if the writer implements optional interfaces to further enrich the attributes.
func Shutdown ΒΆ
Shutdown shuts down the default logger, metric and tracer providers. Each will run on a separate goroutine. It'll return the first error if any happens and cancel the other routines.
It works on any provider that implements the Shutdowner interface. The OTEL standard providers do, for instance. It'll ignore providers that don't.
func Slog ΒΆ
Slog creates an structured logger with an OpenTelemetry handler.
It uses the handler of the default logger from the package, and concatenates with an OpenTelemetry one. This allows the caller to configure a base logger through the standard slog.SetDefault.
Its the caller's responsibility to use the *Context methods to ensure logs retain traceability metadata.
func SpanNameFormatter ΒΆ
SpanNameFormatter builds a HTTP span name using the method as prefix and operation. It fallsback to the request line (as per RFC 7230 section 3.1.1.) if operation is empty.
func WithInstrumentationMiddleware ΒΆ
WithInstrumentationMiddleware creates and enriches a span with HTTP request and response attributes.
Some frameworks provide their own middleware implementation that does roughly the same. You should use either the framework-specific or this one instead of both to reduce the overhead per handler.
func WithMetrics ΒΆ
func WithMetrics(next http.RoundTripper) http.RoundTripper
WithMetrics instruments another HTTP round tripper with request and response metrics.
Types ΒΆ
type ForceFlusher ΒΆ
ForceFlusher represents values that supports forcing a flush process.
type FunctionInfo ΒΆ
type FunctionInfo struct {
Package string
Filename string
Directory string
Filepath string
FunctionName string
LineNumber int
}
FunctionInfo contains details about a function call.
func GetFunctionInfo ΒΆ
func GetFunctionInfo(skip int) *FunctionInfo
GetFunctionInfo reports information about function invocations on the calling goroutine's stack. It parses data from runtime.Caller and runtime.FuncForPC to provide a structured result.
Skip equals zero means the caller of this function.
type Histogram ΒΆ
type Histogram[T Number] interface { Record(ctx context.Context, incr T, options ...metric.RecordOption) }
Histogram represents a histogram metric counter.
type MetricHandlerFn ΒΆ
MetricHandlerFn allows custom logic on how to calculate a metric value during a request. It provides the next handler, the request and the response writer. This handler must call the handler exactly once or else no response will be sent.
type MiddlewareFn ΒΆ
MiddlewareFn is an HTTP handler identity functor, also known as a decorator.
func WithCounterMiddleware ΒΆ
func WithCounterMiddleware[T Number](counter Counter[T], incr T) MiddlewareFn
WithCounterMiddleware wraps another handler, incrementing the counter on each call.
func WithHistogramMiddleware ΒΆ
func WithHistogramMiddleware[T Number]( histogram Histogram[T], handler MetricHandlerFn[T], ) MiddlewareFn
WithHistogramMiddleware wraps another handler, recording a histogram increment on each call.
type MiddlewareWrapperFn ΒΆ
type MiddlewareWrapperFn func(ctx context.Context, w ResponseWriter, handle func())
MiddlewareWrapperFn is a post-response middleware that receives a wrapped response writer capable of reporting status and written bytes length.
type Number ΒΆ
type Number interface {
constraints.Integer | constraints.Float
}
Number is a constraint that permits any numeric type.
type Option ΒΆ added in v0.4.0
Option represents an object that can modify a set of initialization options
func WithLogsExporter ΒΆ added in v0.4.0
WithLogsExporter sets a custom logs exporter
func WithMetricsExporter ΒΆ added in v0.4.0
WithMetricsExporter sets a custom metrics exporter
func WithPropagator ΒΆ added in v0.4.0
func WithPropagator(propagator propagation.TextMapPropagator) Option
WithPropagator sets a custom propagator
func WithTracesExporter ΒΆ added in v0.4.0
func WithTracesExporter(exporter sdktrace.SpanExporter) Option
WithTracesExporter sets a custom span exporter
type Options ΒΆ added in v0.4.0
type Options struct {
LogsExporter sdklog.Exporter
MetricsExporter sdkmetric.Exporter
Propagator propagation.TextMapPropagator
TracesExporter sdktrace.SpanExporter
}
Options contains initialization properties that users can customize
type ResponseContentLengthReporter ΒΆ
type ResponseContentLengthReporter interface {
// ContentLength returns the total number of bytes sent to the client.
ContentLength() int
}
ResponseContentLengthReporter is implemented by http.ResponseWriter values that allow retrieving the status code written to the client.
type ResponseStatusReporter ΒΆ
type ResponseStatusReporter interface {
// Status returns the HTTP status of the request.
Status() int
}
ResponseStatusReporter is implemented by http.ResponseWriter values that allow retrieving the status code written to the client.
type ResponseWriter ΒΆ
type ResponseWriter interface {
http.ResponseWriter
ResponseStatusReporter
ResponseContentLengthReporter
// Unwrap returns the original proxied target.
Unwrap() http.ResponseWriter
}
ResponseWriter extends a http.ResponseWriter to record the status code and content length.
func NewResponseWriter ΒΆ
func NewResponseWriter(w http.ResponseWriter) ResponseWriter
NewResponseWriter wraps a http.ResponseWriter to record the status code and content length.
type RoundTripperFn ΒΆ
RoundTripperFn is a functor that implements http.RoundTripper
type Shutdowner ΒΆ
Shutdowner represents values that support a graceful stop process, also known as shutdown.
type Span ΒΆ
type Span interface {
trace.Span
// Assert changes the span status based on the error. It returns the
// unmodified error.
//
// A non-nil error will record it and set the span status to codes.Error.
// Conversely, a nil error will set the span status to Ok.
Assert(err error) error
// Errorf is a drop-in replacement for fmt.Errorf. It creates a new error
// using fmt.Errorf then calls Assert with it.
Errorf(format string, args ...any) error
}
Span extends the trace.Span with convenience methods.
func SpanFromContext ΒΆ
SpanFromContext returns the current Span from ctx.
If no Span is currently set in ctx an implementation of a Span that performs no operations is returned.
func Start ΒΆ
Start creates a new span and a context containing its reference.
It augments the upstream span with attributes from the caller function and a wrapper that offers utility methods.
func StartNamed ΒΆ
func StartNamed(ctx context.Context, spanName string, opts ...trace.SpanStartOption) (context.Context, Span)
StartNamed creates a new named span and a context containing its reference.
It augments the upstream span with attributes from the caller function and a wrapper that offers utility methods.
type StatusText ΒΆ
type StatusText = string
StatusText represents an HTTP status code text as per IANA definitions and related RFCs.
See https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
func SpanStatusForStatusCode ΒΆ
func SpanStatusForStatusCode(statusCode int) (codes.Code, StatusText)
SpanStatusForStatusCode assigns a span code and message for a HTTP status code.