slog is a built-in package for structured logging (Go 1.21+).
1import "log/slog"23func main() {4 // JSON logger5 logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{6 Level: slog.LevelInfo,7 }))8 slog.SetDefault(logger)910 // Basic logging11 slog.Info("server started", "addr", ":8080")12 // {"time":"2024-01-15T10:30:00Z","level":"INFO","msg":"server started","addr":":8080"}1314 // Attribute grouping15 slog.Info("request handled",16 "method", "GET",17 "path", "/api/users",18 "status", 200,19 "duration", "123ms",20 )2122 // With context23 ctx := context.Background()24 slog.InfoContext(ctx, "processing", "item_id", 42)2526 // Complex attributes27 slog.Info("user created",28 "user", slog.GroupValue(29 slog.String("name", "Alice"),30 slog.Int("age", 25),31 ),32 )33 // {"msg":"user created","user":{"name":"Alice","age":25}}34}3536// Custom handler37type CustomHandler struct {38 handler slog.Handler39}4041func (h *CustomHandler) Handle(ctx context.Context, r slog.Record) error {42 r.Add("service", "my-app")43 return h.handler.Handle(ctx, r)44}4546func (h *CustomHandler) Enabled(ctx context.Context, l slog.Level) bool {47 return h.handler.Enabled(ctx, l)48}4950func (h *CustomHandler) WithAttrs(attrs []slog.Attr) slog.Handler {51 return &CustomHandler{handler: h.handler.WithAttrs(attrs)}52}5354func (h *CustomHandler) WithGroup(name string) slog.Handler {55 return &CustomHandler{handler: h.handler.WithGroup(name)}56}
Advantages: Structured data, JSON format, performance.