Skip to Content

Observability

The observability package provides instrumentation for monitoring and tracing Gofasta applications. It integrates Prometheus for metrics collection and OpenTelemetry for distributed tracing, using standard net/http middleware.

Import

import "github.com/gofastadev/gofasta/pkg/observability"

Metrics

Built-in Metrics

The package automatically registers the following Prometheus metrics:

MetricTypeLabelsDescription
http_requests_totalCountermethod, path, statusTotal number of HTTP requests
http_request_duration_secondsHistogrammethod, pathHTTP request duration in seconds
http_requests_in_flightGaugeNumber of HTTP requests currently being processed

Key Functions

FunctionSignatureDescription
MetricsMiddlewarefunc MetricsMiddleware(next http.Handler) http.HandlerRecords HTTP request metrics (count, duration, in-flight)
MetricsHandlerfunc MetricsHandler() http.HandlerReturns the Prometheus metrics HTTP handler
InitTracerfunc InitTracer(serviceName string) func()Initializes the OpenTelemetry tracer provider and returns a shutdown function
TracingMiddlewarefunc TracingMiddleware(serviceName string) func(http.Handler) http.HandlerCreates spans for HTTP requests and propagates trace context

Usage

Setting Up Metrics

// Expose the Prometheus metrics endpoint mux.Handle("GET /metrics", observability.MetricsHandler()) // Wrap your handler with metrics middleware handler := observability.MetricsMiddleware(mux)

The MetricsMiddleware is a plain func(http.Handler) http.Handler — it wraps the handler directly without requiring a config struct.

Setting Up Tracing

shutdown := observability.InitTracer("my-service") defer shutdown() // Add tracing middleware to create spans for HTTP requests handler := observability.TracingMiddleware("my-service")(mux)

The tracer uses OpenTelemetry with AlwaysSample by default. In production, configure an exporter (OTLP, Jaeger, Zipkin) via the OpenTelemetry SDK.

Combining Metrics and Tracing

shutdown := observability.InitTracer("my-service") defer shutdown() mux.Handle("GET /metrics", observability.MetricsHandler()) // Apply both middleware handler := observability.MetricsMiddleware( observability.TracingMiddleware("my-service")(mux), ) http.ListenAndServe(":8080", handler)

Configuration via config.yaml

observability: metrics_enabled: true tracing_enabled: true metrics_path: /metrics service_name: my-service

Environment variables use the GOFASTA_ prefix (e.g., GOFASTA_OBSERVABILITY_METRICS_ENABLED, GOFASTA_OBSERVABILITY_SERVICE_NAME).

  • Logger — Structured logging complements metrics and traces
  • Health — Health endpoints alongside metrics
  • Middleware — Apply observability middleware to routes
  • Resilience — Retries and circuit breakers expose metrics here
  • Feature Flags — Flag evaluation surfaces in trace span attributes
Last updated on