snippetgoModeratepending
Go structured logging with slog -- stdlib JSON logger
Viewed 0 times
Go 1.21+
slogstructured loggingJSONlog levelhandler1.21
go
Problem
fmt.Println and log.Printf produce unstructured text logs that are hard to parse, filter, and aggregate in production logging systems.
Solution
Go 1.21+ includes slog in the standard library for structured, leveled logging with JSON or text output.
Code Snippets
slog structured logging
import "log/slog"
// JSON handler for production
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelInfo,
}))
slog.SetDefault(logger)
// Structured logging
slog.Info("user logged in",
slog.String("user_id", user.ID),
slog.String("ip", req.RemoteAddr),
slog.Duration("latency", elapsed),
)
// Output: {"time":"...","level":"INFO","msg":"user logged in","user_id":"42","ip":"..."}
// With context (request-scoped)
logger = logger.With(slog.String("request_id", reqID))
logger.Error("database query failed",
slog.String("query", "SELECT..."),
slog.Any("error", err),
)
// Log groups
slog.Info("request",
slog.Group("http",
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.Int("status", status),
),
)Revisions (0)
No revisions yet.