Structured Logging With slog
Emit structured logs with the standard slog package so records carry typed key-value attributes that are easy to filter and correlate.
Code
package main
import (
"log/slog"
"os"
)
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelInfo,
}))
logger.Info("request handled",
slog.String("method", "GET"),
slog.String("path", "/users/42"),
slog.Int("status", 200),
slog.Duration("latency", 0),
)
logger.Error("dependency failed",
slog.String("dependency", "postgres"),
slog.Int("attempt", 3),
)
}Report a problem with this exampleOpens a pre-filled issue on GitHub.