Use structured JSON logging with context, correlation IDs, and severity levels to ensure traceability across microservices. Implement this pattern by initializing a logger with the log/slog package and passing context through your handlers.
import (
"context"
"log/slog"
"os"
)
func init() {
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelInfo,
})))
}
func handleRequest(ctx context.Context) {
logger := slog.With("trace_id", getTraceID(ctx))
logger.Info("request started")
// ... business logic
logger.Info("request completed")
}
- Initialize the logger with
slog.NewJSONHandlerto output structured JSON toos.Stdout. - Create a context-aware logger using
slog.WithContextto attach request-specific data like trace IDs. - Log events at appropriate levels (
Info,Warn,Error) including the trace ID for distributed tracing. - Ensure all service-to-service calls propagate the trace ID in headers to maintain the correlation chain.