Logging Best Practices for Go Microservices

Implement structured JSON logging with context propagation and trace IDs to effectively debug and monitor Go microservices.

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")
}
  1. Initialize the logger with slog.NewJSONHandler to output structured JSON to os.Stdout.
  2. Create a context-aware logger using slog.WithContext to attach request-specific data like trace IDs.
  3. Log events at appropriate levels (Info, Warn, Error) including the trace ID for distributed tracing.
  4. Ensure all service-to-service calls propagate the trace ID in headers to maintain the correlation chain.