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()
}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
