Use slog.LogValuer interface

· 117 words · 1 minute read

log/slog is no longer new in Go. It was introduced in 2023 with Go 1.21. But it is very nice for structural logging. Here’s how to make that structural logging work better for you:

slog is great for both debugging and logging stuff in production. But it’s not great for logging structs or pointers. Fortunately there exists an interface called slog.LogValuer, which you should implement for structs that you log often.

// LogValue implements the slog.LogValuer interface.
func (u *User) LogValue() slog.Value {
	return slog.GroupValue(
		slog.Int64("id", u.ID),
		slog.String("email", u.Email),
		slog.String("name", u.Name),
		slog.Bool("emailVerified", u.EmailVerified),
		slog.String("created", u.Created.Format(time.RFC3339)),
		slog.Any("groups", u.Groups),
		// omit password and other stuff, unlike most pretty-printers
	)
}

// nice logs thanks to LogValue()
slog.Debug("problem", slog.Any("user", user))