observability

package
v0.3.0-alpha.1 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2026 License: MIT Imports: 22 Imported by: 0

README

observability

OpenTelemetry-based tracing, metrics, and health checks for service observability.

Install

go get github.com/kbukum/gokit

Quick Start

package main

import (
    "context"
    "github.com/kbukum/gokit/observability"
)

func main() {
    ctx := context.Background()

    // Initialize tracer
    tracerCfg := observability.DefaultTracerConfig("my-service")
    tp, _ := observability.InitTracer(ctx, &tracerCfg)
    defer tp.Shutdown(ctx)

    // Initialize metrics
    meterCfg := observability.DefaultMeterConfig("my-service")
    mp, _ := observability.InitMeter(ctx, &meterCfg)
    defer mp.Shutdown(ctx)

    // Start a span
    ctx, span := observability.StartSpan(ctx, "process-request")
    observability.SetSpanAttributes(ctx, observability.StringAttribute("user.id", "abc-123"))
    defer span.End()

    // Health checks
    health := observability.NewServiceHealth("my-service", "1.0.0")
    health.AddComponent(observability.Health{
        Name:   "database",
        Status: "healthy",
    })
}

Key Types & Functions

Name Description
InitTracer() / TracerConfig OpenTelemetry tracer setup
InitMeter() / MeterConfig OpenTelemetry metrics setup
StartSpan() / SpanFromContext() Distributed tracing helpers
SetSpanAttributes() / SetSpanError() Span enrichment
Metrics Pre-built metric instruments for requests, operations, errors
OperationContext Combines tracing + metrics for tracked operations
ServiceHealth / HealthChecker Service health aggregation

⬅ Back to main README

Documentation

Overview

Package observability provides OpenTelemetry tracing and metrics integration for comprehensive service observability.

Tracing:

tp, err := observability.InitTracer(ctx, observability.DefaultTracerConfig("my-service"))
defer tp.Shutdown(ctx)

ctx, span := observability.StartSpan(ctx, "my.operation")
defer span.End()

Metrics:

mp, err := observability.InitMeter(ctx, observability.DefaultMeterConfig("my-service"))
defer mp.Shutdown(ctx)

metrics, err := observability.NewMetrics(observability.Meter("my-service"))
metrics.RecordRequestEnd(ctx, observability.RequestMetric{Service: "my-service", Method: "GET /users", Status: "ok", Duration: duration})

Health Checks:

health := observability.NewServiceHealth("my-service", "1.0.0")
health.AddComponent(checker.CheckHealth(ctx))

Index

Constants

View Source
const (
	SpanHTTPRequest = "http.request"
	SpanGRPCCall    = "grpc.call"
	SpanDBQuery     = "db.query"
)

Common span names.

View Source
const (
	AttrServiceName   = "service.name"
	AttrOperationName = "operation.name"
	AttrRequestID     = "request.id"
	AttrUserID        = "user.id"
	AttrDurationMs    = "duration_ms"
	AttrStatus        = "status"
	AttrErrorMessage  = "error.message"
)

Common attribute keys.

Variables

This section is empty.

Functions

func ExtractTraceContext

func ExtractTraceContext(ctx context.Context, carrier TextMapCarrier) context.Context

ExtractTraceContext reads trace context from a transport carrier.

func InitMeter

func InitMeter(ctx context.Context, config *MeterConfig) (*sdkmetric.MeterProvider, error)

InitMeter initializes the OpenTelemetry meter provider. Returns a MeterProvider that should be shut down on application exit.

func InitTracer

func InitTracer(ctx context.Context, config *TracerConfig) (*sdktrace.TracerProvider, error)

InitTracer initializes the OpenTelemetry tracer provider. Returns a TracerProvider that should be shut down on application exit.

func InjectTraceContext

func InjectTraceContext(ctx context.Context, carrier TextMapCarrier)

InjectTraceContext writes the current trace context into a transport carrier.

func Meter

func Meter(name string) metric.Meter

Meter returns a named meter from the global provider.

func PrometheusHandler

func PrometheusHandler() http.Handler

PrometheusHandler returns the HTTP handler that exposes Prometheus metrics.

func RegisterPrometheusEndpoint

func RegisterPrometheusEndpoint(mux *http.ServeMux, path string)

RegisterPrometheusEndpoint registers a metrics endpoint on mux.

func SetSpanAttributes

func SetSpanAttributes(ctx context.Context, attrs ...SpanAttribute)

SetSpanAttributes sets typed attributes on the current span in context.

func SetSpanError

func SetSpanError(ctx context.Context, err error)

SetSpanError records an error on the current span in context.

func SpanFromContext

func SpanFromContext(ctx context.Context) trace.Span

SpanFromContext returns the span from context.

func StartSpan

func StartSpan(ctx context.Context, name string, opts ...trace.SpanStartOption) (context.Context, trace.Span)

StartSpan starts a new span using the default tracer.

func Tracer

func Tracer(name string) trace.Tracer

Tracer returns a named tracer from the global provider.

func WithOperationContext

func WithOperationContext(ctx context.Context, oc *OperationContext) context.Context

WithOperationContext stores an OperationContext in the context.

Types

type AuditEvent

type AuditEvent struct {
	Name       string
	Attributes map[string]string
}

type Auditor

type Auditor interface {
	Audit(context.Context, AuditEvent)
}

type AuditorFunc

type AuditorFunc func(context.Context, AuditEvent)

func (AuditorFunc) Audit

func (f AuditorFunc) Audit(ctx context.Context, event AuditEvent)

type Float64Histogram

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

Float64Histogram wraps a float64 histogram instrument.

func NewFloat64Histogram

func NewFloat64Histogram(meterName, instrumentName string, opts ...InstrumentOption) (*Float64Histogram, error)

NewFloat64Histogram creates a float64 histogram from the named meter.

func (*Float64Histogram) Record

func (h *Float64Histogram) Record(ctx context.Context, value float64, attrs ...MetricAttribute)

Record records a histogram value.

type HeaderCarrier

type HeaderCarrier http.Header

HeaderCarrier adapts HTTP headers for trace propagation.

func (HeaderCarrier) Get

func (c HeaderCarrier) Get(key string) string

Get returns the carrier value for key.

func (HeaderCarrier) Keys

func (c HeaderCarrier) Keys() []string

Keys returns all carrier keys.

func (HeaderCarrier) Set

func (c HeaderCarrier) Set(key, value string)

Set stores value under key.

type Health

type Health struct {
	Name    string            `json:"name"`
	Status  HealthStatus      `json:"status"`
	Message string            `json:"message,omitempty"`
	Details map[string]string `json:"details,omitempty"`
}

Health describes the health of an individual component.

type HealthChecker

type HealthChecker interface {
	CheckHealth(ctx context.Context) Health
}

HealthChecker is implemented by components that can report their health.

type HealthStatus

type HealthStatus string

HealthStatus represents the health state of a component or service.

const (
	HealthStatusUp       HealthStatus = "up"
	HealthStatusDown     HealthStatus = "down"
	HealthStatusDegraded HealthStatus = "degraded"
)

type InstrumentOption

type InstrumentOption func(*instrumentOptions)

InstrumentOption configures a metric instrument.

func WithInstrumentDescription

func WithInstrumentDescription(description string) InstrumentOption

WithInstrumentDescription sets the instrument description.

func WithInstrumentUnit

func WithInstrumentUnit(unit string) InstrumentOption

WithInstrumentUnit sets the instrument unit.

type Int64Counter

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

Int64Counter wraps an int64 counter instrument.

func NewInt64Counter

func NewInt64Counter(meterName, instrumentName string, opts ...InstrumentOption) (*Int64Counter, error)

NewInt64Counter creates an int64 counter from the named meter.

func (*Int64Counter) Add

func (c *Int64Counter) Add(ctx context.Context, value int64, attrs ...MetricAttribute)

Add records a counter increment.

type MapCarrier

type MapCarrier map[string]string

MapCarrier adapts map-backed message headers for trace propagation.

func (MapCarrier) Get

func (c MapCarrier) Get(key string) string

Get returns the carrier value for key.

func (MapCarrier) Keys

func (c MapCarrier) Keys() []string

Keys returns all carrier keys.

func (MapCarrier) Set

func (c MapCarrier) Set(key, value string)

Set stores value under key.

type MeterConfig

type MeterConfig struct {
	// ServiceName is the name of the service.
	ServiceName string
	// ServiceVersion is the version of the service.
	ServiceVersion string
	// Environment is the deployment environment (dev, staging, prod).
	Environment string
	// Endpoint is the OTLP endpoint host:port (e.g., "localhost:4318" for HTTP, "localhost:4317" for gRPC).
	Endpoint string
	// Protocol selects the OTLP wire protocol (HTTP or gRPC). Defaults to HTTP.
	Protocol OTLPProtocol
	// Insecure allows insecure connections (for development).
	Insecure bool
	// Interval is the metric export interval.
	Interval time.Duration
	// SkipGlobalRegistration, when true,
	// prevents InitMeter from mutating the global otel.SetMeterProvider state.
	// See TracerConfig.SkipGlobalRegistration.
	SkipGlobalRegistration bool
}

MeterConfig configures the OpenTelemetry meter provider.

func DefaultMeterConfig

func DefaultMeterConfig(serviceName string) MeterConfig

DefaultMeterConfig returns sensible defaults for development.

type MetricAttribute

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

MetricAttribute is a typed, transport-neutral metric attribute.

func MetricBoolAttribute

func MetricBoolAttribute(key string, value bool) MetricAttribute

MetricBoolAttribute creates a bool metric attribute.

func MetricFloat64Attribute

func MetricFloat64Attribute(key string, value float64) MetricAttribute

MetricFloat64Attribute creates a float64 metric attribute.

func MetricInt64Attribute

func MetricInt64Attribute(key string, value int64) MetricAttribute

MetricInt64Attribute creates an int64 metric attribute.

func MetricIntAttribute

func MetricIntAttribute(key string, value int) MetricAttribute

MetricIntAttribute creates an int metric attribute.

func MetricStringAttribute

func MetricStringAttribute(key, value string) MetricAttribute

MetricStringAttribute creates a string metric attribute.

type Metrics

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

Metrics holds OpenTelemetry metric instruments for common service observability.

func NewMetrics

func NewMetrics(meter metric.Meter) (*Metrics, error)

NewMetrics creates metric instruments on the given meter.

func (*Metrics) RecordError

func (m *Metrics) RecordError(ctx context.Context, errType, component string)

RecordError records an error by type and component.

func (*Metrics) RecordOperation

func (m *Metrics) RecordOperation(ctx context.Context, op OperationMetric)

RecordOperation records an operation execution.

func (*Metrics) RecordRequestEnd

func (m *Metrics) RecordRequestEnd(ctx context.Context, r RequestMetric)

RecordRequestEnd decrements active requests and records the completed request.

func (*Metrics) RecordRequestStart

func (m *Metrics) RecordRequestStart(ctx context.Context)

RecordRequestStart increments the active request count.

type OTLPProtocol

type OTLPProtocol int

OTLPProtocol selects the OTLP exporter wire protocol for traces and metrics. It lets callers pick the transport their collector exposes instead of being locked to HTTP, matching the protocol selection in the sibling kits.

const (
	// OTLPHTTP exports over OTLP/HTTP with protobuf payloads (default; collector port 4318).
	OTLPHTTP OTLPProtocol = iota
	// OTLPGRPC exports over OTLP/gRPC (collector port 4317).
	OTLPGRPC
)

func ParseOTLPProtocol

func ParseOTLPProtocol(value string) (OTLPProtocol, error)

ParseOTLPProtocol maps a config string ("grpc"/"otlp/grpc", "http"/"http/protobuf", or "") to a protocol. An empty value defaults to OTLPHTTP; any other unrecognized value is rejected so a typo such as "grcp" fails configuration instead of silently exporting over the wrong transport.

func (OTLPProtocol) String

func (p OTLPProtocol) String() string

String returns the canonical lowercase name of the protocol.

func (OTLPProtocol) Validate

func (p OTLPProtocol) Validate() error

Validate rejects a protocol value outside the known set, so a directly-assigned enum cannot select an unintended exporter at export time.

type OperationContext

type OperationContext struct {
	ServiceName   string
	OperationName string
	RequestID     string
	UserID        string
	StartTime     time.Time
	Metrics       *Metrics
}

OperationContext holds observability context for a tracked operation.

func NewOperationContext

func NewOperationContext(spec OperationSpec) *OperationContext

NewOperationContext creates a new operation context from spec. If spec.Metrics is nil, metric recording is silently skipped.

func OperationContextFromContext

func OperationContextFromContext(ctx context.Context) *OperationContext

OperationContextFromContext retrieves the OperationContext from context, or nil.

func (*OperationContext) Duration

func (oc *OperationContext) Duration() time.Duration

Duration returns the elapsed time since operation start.

func (*OperationContext) EndOperation

func (oc *OperationContext) EndOperation(ctx context.Context, span trace.Span, status string, err error)

EndOperation ends the span and records request-end metrics.

func (*OperationContext) StartSpanForOperation

func (oc *OperationContext) StartSpanForOperation(ctx context.Context, spanName string) (context.Context, trace.Span)

StartSpanForOperation starts a traced span and records the request start metric.

type OperationMetric

type OperationMetric struct {
	Service   string
	Operation string
	Status    string
	Duration  time.Duration
}

OperationMetric describes an executed operation for Metrics.RecordOperation.

type OperationSpec

type OperationSpec struct {
	ServiceName   string
	OperationName string
	RequestID     string
	UserID        string
	Metrics       *Metrics
}

OperationSpec identifies a tracked operation for NewOperationContext. Metrics may be nil to silently skip metric recording.

type RequestMetric

type RequestMetric struct {
	Service  string
	Method   string
	Status   string
	Duration time.Duration
}

RequestMetric describes a completed request for Metrics.RecordRequestEnd.

type ServiceHealth

type ServiceHealth struct {
	Service    string       `json:"service"`
	Status     HealthStatus `json:"status"`
	Version    string       `json:"version,omitempty"`
	Components []Health     `json:"components,omitempty"`
}

ServiceHealth describes the overall health of a service and its components.

func NewServiceHealth

func NewServiceHealth(service, version string) *ServiceHealth

NewServiceHealth creates a ServiceHealth with status up.

func (*ServiceHealth) AddComponent

func (sh *ServiceHealth) AddComponent(ch Health)

AddComponent adds a component health result and degrades overall status if needed.

type Span

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

Span wraps an OpenTelemetry span behind the kit observability API.

func StartNamedSpan

func StartNamedSpan(ctx context.Context, tracerName, spanName string, opts ...SpanOption) (context.Context, *Span)

StartNamedSpan starts a span from a named tracer.

func (*Span) End

func (s *Span) End()

End completes the span.

func (*Span) RecordError

func (s *Span) RecordError(err error)

RecordError records err on the span.

func (*Span) SetAttributes

func (s *Span) SetAttributes(attrs ...SpanAttribute)

SetAttributes sets attributes on the span.

func (*Span) SetError

func (s *Span) SetError(message string)

SetError marks the span status as error.

type SpanAttribute

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

SpanAttribute is a typed, transport-neutral span attribute.

func BoolAttribute

func BoolAttribute(key string, value bool) SpanAttribute

BoolAttribute creates a bool span attribute.

func Float64Attribute

func Float64Attribute(key string, value float64) SpanAttribute

Float64Attribute creates a float64 span attribute.

func Int64Attribute

func Int64Attribute(key string, value int64) SpanAttribute

Int64Attribute creates an int64 span attribute.

func IntAttribute

func IntAttribute(key string, value int) SpanAttribute

IntAttribute creates an int span attribute.

func StringAttribute

func StringAttribute(key, value string) SpanAttribute

StringAttribute creates a string span attribute.

func StringSliceAttribute

func StringSliceAttribute(key string, value []string) SpanAttribute

StringSliceAttribute creates a string-slice span attribute.

type SpanKind

type SpanKind int

SpanKind identifies the role a span plays in a distributed trace.

const (
	// SpanKindInternal is for work internal to a process.
	SpanKindInternal SpanKind = iota
	// SpanKindServer is for inbound request handling.
	SpanKindServer
	// SpanKindClient is for outbound requests.
	SpanKindClient
	// SpanKindProducer is for message production.
	SpanKindProducer
	// SpanKindConsumer is for message consumption.
	SpanKindConsumer
)

type SpanOption

type SpanOption func(*spanOptions)

SpanOption configures a span without exposing OpenTelemetry option types.

func WithSpanAttributes

func WithSpanAttributes(attrs ...SpanAttribute) SpanOption

WithSpanAttributes adds attributes to the span.

func WithSpanKind

func WithSpanKind(kind SpanKind) SpanOption

WithSpanKind sets the span kind.

type TextMapCarrier

type TextMapCarrier interface {
	Get(key string) string
	Set(key, value string)
	Keys() []string
}

TextMapCarrier is the transport-neutral carrier used for trace propagation.

type TracerConfig

type TracerConfig struct {
	// ServiceName is the name of the service.
	ServiceName string
	// ServiceVersion is the version of the service.
	ServiceVersion string
	// Environment is the deployment environment (dev, staging, prod).
	Environment string
	// Endpoint is the OTLP endpoint host:port (e.g., "localhost:4318" for HTTP, "localhost:4317" for gRPC).
	Endpoint string
	// Protocol selects the OTLP wire protocol (HTTP or gRPC). Defaults to HTTP.
	Protocol OTLPProtocol
	// Insecure allows insecure connections (for development).
	Insecure bool
	// SampleRate is the sampling rate (0.0 to 1.0).
	SampleRate float64
	// SkipGlobalRegistration, when true,
	// prevents InitTracer from mutating the global otel.SetTracerProvider / otel.SetTextMapPropagator state.
	// Callers that want to thread the returned *TracerProvider through DI can opt out of process-global state.
	// Defaults to false to preserve the convenient "init once,
	// instrument anywhere via observability.Tracer(...)" pattern.
	SkipGlobalRegistration bool
}

TracerConfig configures the OpenTelemetry tracer.

func DefaultTracerConfig

func DefaultTracerConfig(serviceName string) TracerConfig

DefaultTracerConfig returns sensible defaults for development.

Jump to

Keyboard shortcuts

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