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:
| Metric | Type | Labels | Description |
|---|---|---|---|
http_requests_total | Counter | method, path, status | Total number of HTTP requests |
http_request_duration_seconds | Histogram | method, path | HTTP request duration in seconds |
http_requests_in_flight | Gauge | — | Number of HTTP requests currently being processed |
Key Functions
| Function | Signature | Description |
|---|---|---|
MetricsMiddleware | func MetricsMiddleware(next http.Handler) http.Handler | Records HTTP request metrics (count, duration, in-flight) |
MetricsHandler | func MetricsHandler() http.Handler | Returns the Prometheus metrics HTTP handler |
InitTracer | func InitTracer(serviceName string) func() | Initializes the OpenTelemetry tracer provider and returns a shutdown function |
TracingMiddleware | func TracingMiddleware(serviceName string) func(http.Handler) http.Handler | Creates 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-serviceEnvironment variables use the GOFASTA_ prefix (e.g., GOFASTA_OBSERVABILITY_METRICS_ENABLED, GOFASTA_OBSERVABILITY_SERVICE_NAME).
Related Pages
- 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