Golang / GoLang Production Patterns and Web Standards Interview Questions
How do you implement structured logging in Go using the slog package?
log/slog was added to the standard library in Go 1.21 as the official structured logging solution. It produces machine-readable output (JSON or key-value pairs) and supports levels, attributes, and handler customisation.
import "log/slog" // Default logger â uses text format to stderr slog.Info("server starting", "port", 8080) slog.Warn("connection slow", "latency_ms", 450, "host", "db.internal") slog.Error("request failed", "error", err, "path", r.URL.Path) // JSON handler for production (machine-parseable) logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ Level: slog.LevelInfo, // minimum level to emit AddSource: true, // include file:line in output })) slog.SetDefault(logger) // Output: {"time":"2024-01-15T...","level":"INFO","msg":"user created","id":42} // Grouping related attributes logger.Info("request completed", slog.Group("request", slog.String("method", r.Method), slog.String("path", r.URL.Path), slog.Int("status", 200), slog.Duration("duration", time.Since(start)), ), ) // Logger with pre-set attributes (child logger) reqLogger := logger.With( slog.String("request_id", requestID), slog.String("user_id", userID), ) reqLogger.Info("fetching user data") reqLogger.Info("user data fetched", "count", len(users)) // Context-aware logging â attach logger to context func withLogger(ctx context.Context, logger *slog.Logger) context.Context { return context.WithValue(ctx, loggerKey{}, logger) } func loggerFromCtx(ctx context.Context) *slog.Logger { if l, ok := ctx.Value(loggerKey{}).(*slog.Logger); ok { return l } return slog.Default() }
More Related questions...