Go 1.27 reference · Files, HTTP and Logging
Go log/slog Function
Write structured logs as key-value pairs in text or JSON, with levels and shared attributes.
Go 1.27 Since 1.21
Syntax
func New(h Handler) *Logger func (l *Logger) Info(msg string, args ...any)
Parameters
| Parameter | Description |
|---|---|
NewJSONHandler / NewTextHandler |
Output format. |
HandlerOptions{Level} |
Minimum level. |
logger.With(...) |
Attributes on every line. |
slog.Group |
Nested attributes. |
Examples
package main
import (
"log/slog"
"os"
)
// dropTime removes the timestamp so this example's output is reproducible.
func dropTime(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey && len(groups) == 0 {
return slog.Attr{}
}
return a
}
func main() {
opts := &slog.HandlerOptions{ReplaceAttr: dropTime}
logger := slog.New(slog.NewJSONHandler(os.Stdout, opts)).With("service", "billing")
logger.Info("charge created", "order", 42, "amount_cents", 1999)
logger.Debug("not shown at the default Info level")
logger.Warn("slow request", slog.Group("http", "path", "/pay", "ms", 1200))
}
Output
{"level":"INFO","msg":"charge created","service":"billing","order":42,"amount_cents":1999}
{"level":"WARN","msg":"slow request","service":"billing","http":{"path":"/pay","ms":1200}}Run this on your computer — see “Get Started” for setup.
package main
import (
"log/slog"
"os"
)
func main() {
opts := &slog.HandlerOptions{Level: slog.LevelDebug, ReplaceAttr: func(g []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
}}
slog.New(slog.NewTextHandler(os.Stdout, opts)).Debug("cache miss", "key", "user:7")
}
Output
level=DEBUG msg="cache miss" key=user:7
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Go 1.21 | Added |
Related
fmt.Printf· Print formatted output using verbs like %v, %+v, %d, %s, %q, %.2f and %T, with width and alignment options.