log/slog
- Go course
- Advanced
- Lesson 59/68
- 4 min
Learn structured logging with log/slog.
log/slog
log/slog, added in Go 1.21, writes structured (key-value) logs. Because fields are recorded instead of plain text, logs can be searched and filtered:
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
logger.Info("sipariş alındı", "id", 42, "tutar", 99.5)
// {"time":"...","level":"INFO","msg":"sipariş alındı","id":42,"tutar":99.5}Levels: Debug, Info, Warn, Error.
Common fields: With
With creates a new logger with fields added to every record, carrying context such as a request ID onto each line:
reqLog := logger.With("istek_id", "a1b2", "yol", "/sepet")
reqLog.Info("başladı")
reqLog.Error("ödeme başarısız", "hata", err)For text output use slog.NewTextHandler: level=INFO msg=başladı istek_id=a1b2.
Practice Text log
Create a logger writing to os.Stdout with slog.NewTextHandler; drop the slog.TimeKey key with ReplaceAttr to remove the time field. Write logger.Info("hazır", "port", 8080).
Starter code
package main
import (
"log/slog"
"os"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"log/slog"
"os"
)
func main() {
opts := &slog.HandlerOptions{
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
},
}
logger := slog.New(slog.NewTextHandler(os.Stdout, opts))
logger.Info("hazır", "port", 8080)
}Expected output
level=INFO msg=hazır port=8080
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 With default settings, why doesn't <code>logger.Debug(...)</code> show up?
- It errors
- The default level is Info; Debug is below it Correct answer
- Debug was removed
- The JSON handler doesn't support Debug
Explanation: Records below Info are not written unless HandlerOptions{Level: slog.LevelDebug} is given.
2 Add a common field
reqLog := logger.____("istek_id", id)
reqLog := logger.With("istek_id", id)
Explanation: With returns a new logger that adds the given fields to all later records.
3 slog parts
| Term | Meaning |
|---|---|
slog.NewJSONHandler |
JSON output |
slog.NewTextHandler |
key=value output |
logger.With |
Common fields |
slog.LevelDebug |
Most detailed level |