// Start a span (if not already in a trace, this will start a new one)
tracer := otel.GetTracerProvider().Tracer("my-tracer")
ctx, span := tracer.Start(ctx, r.URL.Path)
defer span.End()
// Set the span in the context for the handler
r = r.WithContext(ctx)
// Generate a correlation ID if not present (for logging)
correlationID := r.Header.Get("X-Correlation-ID")
if correlationID == "" {
correlationID = generateID()
}
// We can also set the correlation ID as a span attribute
span.SetAttributes(attribute.String("correlation_id", correlationID))
// Use a response writer that captures status code
rw := &responseWriter{ResponseWriter: w, statusCode: 200}
start := time.Now()
next.ServeHTTP(rw, r)
duration := time.Since(start).Seconds()
// Record metrics
statusCode := rw.statusCode
requestsTotal.WithLabelValues(r.Method, r.URL.Path, strconv.Itoa(statusCode)).Inc()
requestDuration.WithLabelValues(r.Method, r.URL.Path).Observe(duration)
// Set span status based on HTTP status
if statusCode >= 400 {
span.SetStatus(codes.Error, fmt.Sprintf("HTTP %d", statusCode))
span.RecordError(fmt.Errorf("request failed with status %d", statusCode))
}
// Log the request with correlation ID and other details
logger.Info("HTTP request",
zap.String("method", r.Method),
zap.String("path", r.URL.Path),
zap.Int("status", statusCode),
zap.Duration("duration", duration),
zap.String("trace_id", trace.SpanFromContext(ctx).SpanContext().TraceID().String()),
zap.String("correlation_id", correlationID),
)
})
}
Note: The above example uses OpenTelemetry and a custom response writer.
Sampling configuration for traces:
In OpenTelemetry, we can set a sampler in the tracer provider:
import "go.opentelemetry.io/otel/sdk/trace"
sampler := trace.TraceIdRatioBased(0.01) // 1% of traces
tp := trace.NewTracerProvider(
trace.WithSampler(sampler),
// ... other options (batcher, exporter)
)
otel.SetTracerProvider(tp)
Dashboards:
In Grafana, we can create panels:
For latency:
code
histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[5m])) by (le, method, path))
For traffic (RPS):
code
sum(rate(http_requests_total[5m])) by (method, path)
We can define SLOs (e.g., 99.9% of requests succeed within 200ms) and then calculate error budget burn.
Example SLO:
code
success = sum(rate(http_requests_total{status=~"2.."}[30d]))
total = sum(rate(http_requests_total[30d]))
success_ratio = success / total
Then set an alert when success_ratio < 0.999 for a certain period.
We can also track error budget burn rate.
Conclusion:
This is a comprehensive observability setup. The exact tools and configuration may vary, but the principles are the same.
Remember to:
Use structured logging with correlation IDs.
Instrument metrics (counters, histograms, gauges) for the golden signals.
Use distributed tracing with context propagation.
Set up dashboards and alerts based on SLOs and golden signals.
Adjust sampling based on volume and cost.
This design should help in monitoring, debugging, and understanding the system.
I'll provide a comprehensive observability implementation framework with concrete examples. This covers the full spectrum of production-ready observability.
DEBUG: Development details, filter out in production
INFO: Business operations (order created, user logged in)
WARN: Recoverable issues (retryable failures, deprecated API usage)
ERROR: Failed operations with stack traces
FATAL: Service crashes
Example log line:
json
{"timestamp":"2024-01-15T10:30:45.123Z","level":"ERROR","service":"order-service","trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","span_id":"00f067aa0ba902b7","message":"failed to process payment","error":"connection timeout","order_id":"ORD-789","user_id":"user-123","duration_ms":1500}
# Find all logs for a specific trace
{app="order-service"} | trace_id="4bf92f3577b34da6a3ce929d0e0e4736"
# Error rate by service
sum(count_over_time({app=~".+"} |= "error" [5m])) by (app)
/
sum(count_over_time({app=~".+"} [5m])) by (app)
# Latency correlation with errors
histogram_quantile(0.95,
sum(rate(http_request_duration_seconds_bucket{app="order-service"}[5m])) by (le)
)
> 1
and
sum(rate({app="order-service"} |= "error" [5m])) > 0.1
Correlation: All three signals share traceID/spanID
SLOs: Define error budget policies and burn rate alerts
Documentation: Schemas for logs/metrics/traces, runbooks for alerts
12. PRODUCTION TIPS
Start with SLOs: Define error budget before building alerts
Cardinality control: Limit label values (avoid high-cardinality labels like user IDs)
Sampling first: Implement sampling before full rollout to control costs
Dashboard hierarchy:
Service level (golden signals)
Infrastructure (USE)
Business (conversion rates, revenue impact)
Alert fatigue prevention:
Group related alerts
Set appropriate for durations
Use inhibition rules (e.g., don't alert on latency if service is down)
Cost management:
Trace sampling rate based on traffic volume
Log retention policies by level
Metrics aggregation and downsampling
This framework provides a production-ready observability stack that can scale from single service to large distributed systems. Remember to iteratively improve based on actual incident learnings and business needs.