Slog ReplaceAttr Rewrites JSON Fields

Rewrite JSON log fields with slog.HandlerOptions.ReplaceAttr: rename the time key, lowercase levels, and redact sensitive keys before they reach output.

GoSecurity Boundaries

Code

snippet
package main

import (
	"log/slog"
	"os"
	"strings"
	"time"
)

func main() {
	logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
		// ReplaceAttr 会逐个经过每条记录的属性:改键名、改值,或返回替换值
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			switch a.Key {
			case slog.TimeKey: // 时间键改名并转成 UTC 字符串
				return slog.String("ts", a.Value.Time().UTC().Format(time.RFC3339))
			case slog.LevelKey: // 级别值改为小写字符串
				return slog.String("level", strings.ToLower(a.Value.Level().String()))
			case "password": // 敏感键无论值是什么都替换为掩码
				return slog.String("password", "[redacted]")
			}
			return a
		},
	}))

	logger.Info("user signed in", "user", "alice", "password", "hunter2")
}

How the code is organised

Under the hood: the function main.

Points of care

  • Nothing but built-in APIs, so a supply-chain review has nothing to check.

Using it

The one callable at the centre: func main()

Key statements

return slog.String("level", strings.ToLower(a.Value.Level().String()))
return slog.String("ts", a.Value.Time().UTC().Format(time.RFC3339))
return slog.String("password", "[redacted]")

Interactive Tools for This Topic

FAQ

How do you run Slog ReplaceAttr Rewrites JSON Fields?
The runtime alone is enough: execute the file as a complete program.