gotell

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: May 20, 2025 License: MIT Imports: 37 Imported by: 1 module, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README ΒΆ

gotell

Golang OTEL library, an opinionated thin-wrapper over the OpenTelemetry SDK

Go Reference GitHub Issues GitHub Pull Requests Codecov

GitHub branch status License


πŸ“ Table of Contents

🧐 About

Gotell is an opinionated thin wrapper on top of the OpenTelemetry Go SDK. It applies semantic convention metrics and attributes for you so you don't have to.

The name gotell comes from go + otel (OpenTelemetry) + library. πŸ˜‰

🏁 Getting Started

Run go get github.com/wwmoraes/gotell or add the repository to your imports then run go mod tidy.

πŸ”§ Running the tests

Run task test πŸ˜„

🎈 Usage

package main

import (
  "context"
  "errors"
  "fmt"
  "net"
  "net/http"
  "os"
  "os/signal"
  "time"

  telemetry "github.com/wwmoraes/gotell"
  "go.opentelemetry.io/otel/attribute"
  "go.opentelemetry.io/otel/sdk/resource"
)

const (
  NAMESPACE = "github.com/wwmoraes/gotell"
  NAME      = "http-server"
)

var version = "0.0.0"

func main() {
  ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
  defer cancel()

  hostname, err := os.Hostname()
  if err != nil {
    fmt.Fprintln(os.Stderr, err)
    os.Exit(1)
  }

  err = telemetry.Initialize(ctx, resource.NewSchemaless(
    attribute.String("service.name", NAME),
    attribute.String("service.namespace", NAMESPACE),
    attribute.String("service.version", version),
    attribute.String("host.id", hostname),
  ))
  if err != nil {
    fmt.Fprintln(os.Stderr, err)
    os.Exit(1)
  }

  log := telemetry.Logr(ctx)

  mux := http.NewServeMux()

  mux.Handle("/", telemetry.WithInstrumentationMiddleware(http.HandlerFunc(helloHandler)))

  listener, err := net.Listen("tcp4", "127.0.0.1:0")
  if !errors.Is(err, http.ErrServerClosed) {
    log.Error(err, "failed to create listener")
    os.Exit(1)
  }

  server := http.Server{
    Handler:           mux,
    ReadTimeout:       time.Minute / 2,
    ReadHeaderTimeout: time.Minute / 2,
  }

  log.Info("serving HTTP", "address", listener.Addr().String())

  err = server.Serve(listener)
  if !errors.Is(err, http.ErrServerClosed) {
    log.Error(err, "server stopped")
  }
}

func helloHandler(w http.ResponseWriter, r *http.Request) {
  ctx, span := telemetry.Start(r.Context())
  defer span.End()

  log := telemetry.Logr(ctx)

  log.Info("hello handler triggered")

  name := r.URL.Query().Get("name")
  if name == "" {
    name = "stranger"
  }

  span.SetAttributes(attribute.String("name", name))

  fmt.Fprintf(w, "hello %s!", name)
}

πŸ”§ Built Using

πŸ§‘β€πŸ’» Authors

πŸŽ‰ Acknowledgements

Documentation ΒΆ

Overview ΒΆ

Package gotell extends the OpenTelemetry SDK with helpful utilities and sane defaults.

Index ΒΆ

Constants ΒΆ

View Source
const (
	// NAME contains the package name. It's used to separate all OpenTelemetry
	// instances from the upstream.
	NAME = "github.com/wwmoraes/gotell"
)

Variables ΒΆ

View Source
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
)
View Source
var ErrForceFlush = errors.New("failed to force flush provider")

ErrForceFlush happens when a provider fails to force flush

View Source
var ErrShutdownFailed = errors.New("failed to shutdown provider")

ErrShutdownFailed happens when a provider fails to shutdown

Functions ΒΆ

func ContextLabeler ΒΆ

func ContextLabeler(ctx context.Context) (context.Context, *otelhttp.Labeler)

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 ΒΆ

func FilterHeaders(headers http.Header, includedKeys ...string) http.Header

FilterHeaders returns a subset of headers for the given keys. The values are not copies.

func ForceFlush ΒΆ

func ForceFlush(ctx context.Context) error

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 ΒΆ

func FunctionAttributes(skip int) []attribute.KeyValue

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 ΒΆ

func Initialize(ctx context.Context, res *resource.Resource, options ...Option) error

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 Logger ΒΆ

func Logger() log.Logger

Logger returns a new logger configured by gotell.

func Logr ΒΆ

func Logr(ctx context.Context) logr.Logger

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 Meter ΒΆ

func Meter() metric.Meter

Meter returns a new meter configured by gotell.

func OpenSQL ΒΆ

func OpenSQL(driverName, dataSourceName string) (*sql.DB, error)

OpenSQL wraps database/sql.Open to add metadata and instrumentation.

func RequestAttributes ΒΆ

func RequestAttributes(req *http.Request) []attribute.KeyValue

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 ΒΆ

func Shutdown(ctx context.Context) error

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 ΒΆ

func Slog() *slog.Logger

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 ΒΆ

func SpanNameFormatter(operation string, req *http.Request) string

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 Tracer ΒΆ

func Tracer(ctx context.Context) trace.Tracer

Tracer returns a new tracer configured by gotell.

func WithInstrumentationMiddleware ΒΆ

func WithInstrumentationMiddleware(next http.Handler) http.Handler

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 Counter ΒΆ

type Counter[T Number] interface {
	Add(ctx context.Context, incr T, options ...metric.AddOption)
}

Counter represents an additive metric counter.

type ForceFlusher ΒΆ

type ForceFlusher interface {
	ForceFlush(ctx context.Context) error
}

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 ΒΆ

type MetricHandlerFn[T any] func(http.Handler, http.ResponseWriter, *http.Request) T

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 ΒΆ

type MiddlewareFn func(http.Handler) http.Handler

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

type Option interface {
	Apply(opts *Options) error
}

Option represents an object that can modify a set of initialization options

func WithLogsExporter ΒΆ added in v0.4.0

func WithLogsExporter(exporter sdklog.Exporter) Option

WithLogsExporter sets a custom logs exporter

func WithMetricsExporter ΒΆ added in v0.4.0

func WithMetricsExporter(exporter sdkmetric.Exporter) Option

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 OptionFn ΒΆ added in v0.4.0

type OptionFn func(opts *Options) error

OptionFn is a function that implements Option

func (OptionFn) Apply ΒΆ added in v0.4.0

func (fn OptionFn) Apply(opts *Options) error

Apply executes the function to apply its changes

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

func NewOptions ΒΆ added in v0.4.0

func NewOptions(ctx context.Context, options ...Option) (*Options, error)

NewOptions creates a new Options object, applies any Option to it, and ensures defaults apply before returning a valid object

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 ΒΆ

type RoundTripperFn func(req *http.Request) (*http.Response, error)

RoundTripperFn is a functor that implements http.RoundTripper

func (RoundTripperFn) RoundTrip ΒΆ

func (fn RoundTripperFn) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip executes an HTTP transaction.

See https://pkg.go.dev/net/http#RoundTripper

type Shutdowner ΒΆ

type Shutdowner interface {
	Shutdown(ctx context.Context) error
}

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 ΒΆ

func SpanFromContext(ctx context.Context) Span

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 ΒΆ

func Start(ctx context.Context, opts ...trace.SpanStartOption) (context.Context, Span)

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.

Directories ΒΆ

Path Synopsis
Package logging provides support for multiple upstream logger libraries.
Package logging provides support for multiple upstream logger libraries.

Jump to

Keyboard shortcuts

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