observability

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2026 License: MIT Imports: 15 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
    tp, _ := observability.InitTracer(ctx, observability.DefaultTracerConfig("my-service"))
    defer tp.Shutdown(ctx)

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

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

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

Key Types & Functions

Name Description
InitTracer() / TracerConfig OpenTelemetry tracer setup
InitMeter() / MeterConfig OpenTelemetry metrics setup
StartSpan() / SpanFromContext() Distributed tracing helpers
SetSpanAttribute() / 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, "my-service", "GET /users", "ok", 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 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 Meter

func Meter(name string) metric.Meter

Meter returns a named meter from the global provider.

func SetSpanAttribute

func SetSpanAttribute(ctx context.Context, key string, value any)

SetSpanAttribute sets an attribute 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 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 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 HTTP endpoint host:port (e.g., "localhost:4318").
	Endpoint string
	// Insecure allows insecure connections (for development).
	Insecure bool
	// Interval is the metric export interval.
	Interval time.Duration
}

MeterConfig configures the OpenTelemetry meter provider.

func DefaultMeterConfig

func DefaultMeterConfig(serviceName string) MeterConfig

DefaultMeterConfig returns sensible defaults for development.

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, service, operation, status string, duration time.Duration)

RecordOperation records an operation execution.

func (*Metrics) RecordRequestEnd

func (m *Metrics) RecordRequestEnd(ctx context.Context, service, method, status string, duration time.Duration)

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 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(serviceName, operationName, requestID, userID string, metrics *Metrics) *OperationContext

NewOperationContext creates a new operation context. If 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 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 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 HTTP endpoint host:port (e.g., "localhost:4318").
	Endpoint string
	// Insecure allows insecure connections (for development).
	Insecure bool
	// SampleRate is the sampling rate (0.0 to 1.0).
	SampleRate float64
}

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