Golang / GoLang Production Patterns and Web Standards Interview Questions
How do you add observability (metrics and distributed tracing) to a Go service?
Production Go services expose Prometheus metrics and OpenTelemetry traces. Both integrate with Go's standard HTTP server and context-based propagation.
// Prometheus metrics with the standard prometheus/client_golang library import ( "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" ) var ( httpRequestsTotal = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "http_requests_total", Help: "Total number of HTTP requests", }, []string{"method", "path", "status"}, ) httpRequestDuration = prometheus.NewHistogramVec( prometheus.HistogramOpts{ Name: "http_request_duration_seconds", Help: "HTTP request duration in seconds", Buckets: prometheus.DefBuckets, }, []string{"method", "path"}, ) ) func init() { prometheus.MustRegister(httpRequestsTotal, httpRequestDuration) } // Metrics middleware func metricsMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() lrw := &statusResponseWriter{ResponseWriter: w, status: 200} next.ServeHTTP(lrw, r) dur := time.Since(start).Seconds() path := r.URL.Path httpRequestsTotal.WithLabelValues(r.Method, path, strconv.Itoa(lrw.status)).Inc() httpRequestDuration.WithLabelValues(r.Method, path).Observe(dur) }) } // Expose metrics endpoint mux.Handle("GET /metrics", promhttp.Handler()) // OpenTelemetry tracing (simplified) // otel.SetTracerProvider(tp) // tracer := otel.Tracer("myservice") // ctx, span := tracer.Start(ctx, "operationName") // defer span.End() // span.SetAttributes(attribute.String("user.id", userID))
More Related questions...