Structured logging in Go
log/slog writes key-value pairs, at a level, in text or JSON.
func logging() string {
var out strings.Builder
logger := slog.New(slog.NewJSONHandler(&out, &slog.HandlerOptions{
Level: slog.LevelInfo,
}))
logger.Info("loaded content", "steps", 1015, "langs", 10)
logger.Debug("not shown at info level")
request := logger.With("request_id", "abc123")
request.Warn("slow response", slog.Duration("took", 250*time.Millisecond))
return fmt.Sprintf("%d log lines",
len(strings.Split(strings.TrimSpace(out.String()), "\n")))
}
How it works
- Attributes are pairs after the message.
Withreturns a logger that carries fields for you.- A JSON handler is what a log pipeline wants.
Keywords and builtins used here
funclenreturnstringvar
The run, in numbers
- Lines
- 15
- Characters to type
- 460
- Tokens
- 116
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 66 seconds.
Step 2 of 2 in Programs & logging, step 15 of 26 in Standard library & project layout.