Hasty Briefsbeta

Logging in Go with Slog: A Practitioner's Guide

4 days ago
  • #Structured-Logging
  • #Go
  • #Logging
  • Go 1.21 introduced `log/slog`, a native structured logging solution.
  • `slog` is built around three core types: `Logger`, `Handler`, and `Record`.
  • The `Logger` provides methods like `Info()`, `Debug()`, and `Error()`.
  • The `Handler` processes `Records` and determines log output format and destination.
  • The `Record` contains log event details like time, severity, message, and attributes.
  • `slog` supports contextual logging with `slog.Attr` for structured key-value pairs.
  • Linters like `sloglint` enforce best practices for consistent logging.
  • `slog` offers four severity levels: `DEBUG`, `INFO`, `WARN`, and `ERROR`.
  • Custom log levels can be created and mapped using `ReplaceAttr`.
  • Built-in handlers include `JSONHandler` and `TextHandler` for different output formats.
  • Third-party handlers extend functionality with features like sampling and colorization.
  • Contextual logging patterns include global logger, embedding logger in context, and explicit passing.
  • The `LogValuer` interface controls how custom types appear in logs.
  • Error logging can be enriched with structured context and stack traces.
  • `slog` performance is slower than `zerolog` and `zap` but optimized for common use cases.
  • Centralized observability pipelines can ingest `slog` logs for correlation with traces and metrics.