You may find cases where you wish to control how a value is logged, differently than how it’s used in other contexts. The log/slog package gives you a lot of flexibility in this regard, for custom types:
Customizing a type’s logging behavior
If a type implements the LogValuer interface, the Value returned from its LogValue method is used for logging. You can use this to control how values of the type appear in logs. For example, you can redact secret information like passwords, or gather a struct’s fields in a Group. See the examples under LogValuer for details.
A LogValue method may return a Value that itself implements LogValuer. The Value.Resolve method handles these cases carefully, avoiding infinite loops and unbounded recursion. Handler authors and others may wish to use Value.Resolve instead of calling LogValue directly.
We’ll look at specific examples, when we get to the LogValuer part of the documentation, but for now, a few examples where this could be useful:
- Secret redaction (as mentioned in the quote above)
- Defer expensive operations until actually used (
LogValuerisn’t evaluated for logs that aren’t actually produced) - Any time you want the log output to be different than other output