telemetry

package
v0.1.53 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2026 License: MIT Imports: 23 Imported by: 0

README

telemetry

Observability - metrics, tracing, and logging integration.

What It Does

Provides Prometheus metrics and OpenTelemetry tracing with HTTP/gRPC middleware.

Metrics

Initialization
telemetry.InitMetrics(&telemetry.MetricsConfig{
    ServiceName: "my-service",
    Enabled:     true,
    Buckets:     prometheus.DefBuckets,  // or custom
})
Recording Metrics
// HTTP requests
telemetry.RecordHTTPRequest("my-service", "GET", "/users", 200, duration)
telemetry.IncrementHTTPRequestsInFlight("my-service")
telemetry.DecrementHTTPRequestsInFlight("my-service")

// Database queries
telemetry.RecordDBQuery("my-service", "SELECT", true, duration)

// External API calls
telemetry.RecordExternalAPICall("my-service", "stripe", "/charges", true, duration)

// Cache
telemetry.RecordCacheHit("my-service", "users")
telemetry.RecordCacheMiss("my-service", "users")
Exposing Metrics
// Add to your HTTP server
router.Get("/metrics", func(c *fiber.Ctx) error {
    return c.SendString(telemetry.Handler().ServeHTTP(c.Response()))
})
// Or use promhttp.Handler() directly

Tracing

Initialization
// Development (prints to stdout)
telemetry.InitTracing(telemetry.DefaultConfig("my-service"))

// Production (sends to OTLP collector)
telemetry.InitTracing(&telemetry.TraceConfig{
    ServiceName:    "my-service",
    ServiceVersion: "1.0.0",
    Environment:    "production",
    Exporter:       telemetry.ExporterOTLP,
    OTLPEndpoint:   "localhost:4317",
    TLSEnabled:     true,
    SampleRate:     0.1,  // 10% of traces
})
Creating Spans
// Basic span
ctx, span := telemetry.StartSpan(ctx, "fetch-user")
defer span.End()

// With attributes
ctx, span := telemetry.StartSpanWithAttributes(ctx, "fetch-user", map[string]interface{}{
    "user_id": userID,
})

// Add attributes to current span
telemetry.AddAttributes(ctx, map[string]interface{}{
    "key": "value",
})

// Add event
telemetry.AddEvent(ctx, "cache-miss", map[string]interface{}{
    "key": "user:123",
})

// Record error
telemetry.RecordError(ctx, err)
Context Helpers
// Add to context for propagation
ctx = telemetry.WithOperation(ctx, "user.create")
ctx = telemetry.WithComponent(ctx, "database")
ctx = telemetry.WithUserID(ctx, userID)
ctx = telemetry.WithRequestID(ctx, requestID)

// Get trace info
traceID := telemetry.GetTraceID(ctx)
spanID := telemetry.GetSpanID(ctx)
HTTP Middleware
// Auto-trace HTTP requests
router.Use(telemetry.TraceHTTPMiddleware("my-service"))
gRPC Middleware
// Auto-trace gRPC calls
server := grpc.NewServer(
    grpc.UnaryInterceptor(telemetry.TraceGRPCMiddleware("my-service")),
)
Context Propagation
// Inject trace context into outgoing requests (e.g., to another service)
headers := telemetry.InjectContext(ctx)
// Add headers to HTTP request or gRPC metadata

// Extract trace context from incoming requests
ctx := telemetry.ExtractContext(ctx, headers)
Shutdown
// Call on service shutdown
telemetry.ShutdownTracing(ctx)

Fiber Integration

// Use built-in middleware
app.Use(telemetry.FiberMiddleware("my-service"))
// Adds: request duration metrics, tracing

HTTP Middleware (for net/http)

// Use with standard library
handler := telemetry.HTTPMiddleware("my-service", nextHandler)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddAttributes added in v0.1.2

func AddAttributes(ctx context.Context, attrs map[string]interface{})

AddAttributes adds attributes to the current span in the context

func AddEvent added in v0.1.2

func AddEvent(ctx context.Context, name string, attrs map[string]interface{})

AddEvent adds an event to the current span in the context

func AddSpanAttributes

func AddSpanAttributes(ctx context.Context, attrs ...attribute.KeyValue)

AddSpanAttributes adds attributes to the current span

func AddSpanEvent

func AddSpanEvent(ctx context.Context, name string, attrs ...attribute.KeyValue)

AddSpanEvent adds an event to the current span

func DecrementHTTPRequestsInFlight

func DecrementHTTPRequestsInFlight(service string)

DecrementHTTPRequestsInFlight decrements the in-flight HTTP requests gauge

func ExtractContext added in v0.1.2

func ExtractContext(ctx context.Context, headers map[string]string) context.Context

ExtractContext extracts trace context from a map

func FiberMiddleware

func FiberMiddleware(serviceName string) fiber.Handler

FiberMiddleware returns Fiber middleware that records HTTP request metrics

func GetSpanID

func GetSpanID(ctx context.Context) string

GetSpanID returns the span ID from the context if available

func GetTraceID

func GetTraceID(ctx context.Context) string

GetTraceID returns the trace ID from the context if available

func HTTPMiddleware

func HTTPMiddleware(serviceName string) func(http.Handler) http.Handler

HTTPMiddleware returns middleware that records HTTP request metrics

func Handler

func Handler() http.Handler

Handler returns the Prometheus metrics HTTP handler

func IncrementHTTPRequestsInFlight

func IncrementHTTPRequestsInFlight(service string)

IncrementHTTPRequestsInFlight increments the in-flight HTTP requests gauge

func InitMetrics added in v0.1.2

func InitMetrics(cfg *MetricsConfig)

InitMetrics initializes the metrics with custom configuration

func InitTracing

func InitTracing(cfg *TraceConfig) error

InitTracing initializes the OpenTelemetry tracing

func InjectContext added in v0.1.2

func InjectContext(ctx context.Context) map[string]string

InjectContext injects trace context into a map for propagation

func IsInitialized

func IsInitialized() bool

IsInitialized returns whether tracing has been initialized

func IsMetricsEnabled added in v0.1.2

func IsMetricsEnabled() bool

IsMetricsEnabled returns whether metrics are enabled

func IsRecording added in v0.1.2

func IsRecording(ctx context.Context) bool

IsRecording returns whether the current span is recording

func RecordAIRequest

func RecordAIRequest(service, model string, success bool, duration time.Duration)

RecordAIRequest records an AI request

func RecordCacheHit

func RecordCacheHit(service, cache string)

RecordCacheHit records a cache hit

func RecordCacheMiss

func RecordCacheMiss(service, cache string)

RecordCacheMiss records a cache miss

func RecordDBQuery

func RecordDBQuery(service, operation string, success bool, duration time.Duration)

RecordDBQuery records a database query

func RecordError

func RecordError(ctx context.Context, err error, opts ...trace.EventOption)

RecordError records an error on the current span

func RecordExternalAPICall

func RecordExternalAPICall(service, provider, endpoint string, success bool, duration time.Duration)

RecordExternalAPICall records an external API call

func RecordGRPCRequest

func RecordGRPCRequest(service, method, status string, duration time.Duration)

RecordGRPCRequest records a gRPC request

func RecordHTTPRequest

func RecordHTTPRequest(service, method, endpoint string, statusCode int, duration time.Duration)

RecordHTTPRequest records an HTTP request

func RecordTokenSync

func RecordTokenSync(service string, success bool, duration time.Duration)

RecordTokenSync records a token sync operation

func SetDBConnections

func SetDBConnections(service string, count float64)

SetDBConnections sets the number of active database connections

func SetSpanStatus

func SetSpanStatus(ctx context.Context, code codes.Code, description string)

SetSpanStatus sets the status of the current span

func ShutdownTracing

func ShutdownTracing(ctx context.Context) error

ShutdownTracing shuts down the trace provider and flushes remaining spans

func StartSpan

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

StartSpan starts a new span with the given name

func StartSpanWithAttributes added in v0.1.2

func StartSpanWithAttributes(ctx context.Context, name string, attrs map[string]interface{}) (context.Context, trace.Span)

StartSpanWithAttributes creates a new span with attributes

func TraceGRPCMiddleware added in v0.1.2

func TraceGRPCMiddleware(serviceName string) grpc.UnaryServerInterceptor

TraceGRPCMiddleware returns a gRPC unary interceptor that traces RPC calls

func TraceHTTPMiddleware added in v0.1.2

func TraceHTTPMiddleware(serviceName string) func(http.Handler) http.Handler

TraceHTTPMiddleware returns a middleware that traces HTTP requests

func Tracer

func Tracer() trace.Tracer

Tracer returns the global tracer instance

func WithComponent added in v0.1.2

func WithComponent(ctx context.Context, component string) context.Context

WithComponent returns a context with a component name attribute

func WithOperation added in v0.1.2

func WithOperation(ctx context.Context, operation string) context.Context

WithOperation returns a context with an operation name attribute

func WithRequestID added in v0.1.2

func WithRequestID(ctx context.Context, requestID string) context.Context

WithRequestID returns a context with a request ID attribute

func WithSpan

func WithSpan(ctx context.Context, name string, fn func(context.Context) error) error

WithSpan creates a span and runs the given function within it

func WithUserID added in v0.1.2

func WithUserID(ctx context.Context, userID string) context.Context

WithUserID returns a context with a user ID attribute

Types

type ExporterType

type ExporterType string

ExporterType defines the type of trace exporter

const (
	ExporterNone   ExporterType = "none"
	ExporterStdout ExporterType = "stdout"
	ExporterOTLP   ExporterType = "otlp"
)

type MetricsConfig added in v0.1.2

type MetricsConfig struct {
	ServiceName string
	Enabled     bool
	Buckets     []float64
}

MetricsConfig holds configuration for metrics

func DefaultMetricsConfig added in v0.1.2

func DefaultMetricsConfig(serviceName string) *MetricsConfig

DefaultMetricsConfig returns default metrics configuration

type TraceConfig

type TraceConfig struct {
	ServiceName    string
	ServiceVersion string
	Environment    string
	Exporter       ExporterType
	OTLPEndpoint   string
	SampleRate     float64
	TLSEnabled     bool
	TLSConfig      *tls.Config
}

TraceConfig holds configuration for tracing

func DefaultConfig

func DefaultConfig(serviceName string) *TraceConfig

DefaultConfig returns a default trace configuration

Jump to

Keyboard shortcuts

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