Lazy Log Values With slog LogValuer
Resolve expensive values only when a record is emitted: implement slog.LogValuer so the handler calls LogValue lazily instead of eagerly at call time.
Code
package main
import (
"log/slog"
"os"
)
// 昂贵值的包装:若调用方直接求值,即使级别被过滤也照付成本
type rowTotal struct{ cents int64 }
func (r rowTotal) LogValue() slog.Value {
// 只有 handler 决定真正写出这条记录时才会进入这里
return slog.Int64Value(r.cents)
}
func main() {
logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
total := rowTotal{cents: 12_500}
logger.Info("order settled", slog.Any("total", total))
logger.Debug("verbose dump", slog.Any("total", total)) // 默认 Info 级别:整条被过滤
}Where the laziness lives
rowTotal implements LogValue() slog.Value, returning slog.Int64Value(r.cents). The struct is passed with slog.Any("total", total), which stores the wrapper untouched; only when the handler decides to emit the record does it call LogValue to resolve the real value. That is the difference from formatting the number at the call site — with an eager value, even a filtered record would have paid the computation cost.
What the handler emits
The logger is slog.New(slog.NewTextHandler(os.Stdout, nil)), so the default level is Info. The run prints one text record whose stable parts are:
level=INFO msg="order settled" total=12500
(with a time= field prefix that varies per run). total=12500 is LogValue’s Int64Value(r.cents) rendered as plain text. The Debug call passes the same wrapper, but the whole record is filtered out before any attribute is resolved — nothing from it appears, and LogValue never runs for it.
The line that defers the cost
func (r rowTotal) LogValue() slog.Value {
// 只有 handler 决定真正写出这条记录时才会进入这里
return slog.Int64Value(r.cents)
}
For an expensive field — a computed aggregate, a serialization — this method is the boundary: handler-emitted records pay for it, dropped records do not.
Interactive Tools for This Topic
FAQ
- How do you run Lazy Log Values With slog LogValuer?
- Nothing to install first — run the file and the program does the rest.
Report a problem with this exampleOpens a pre-filled issue on GitHub.