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.
Code
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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- How do you run Slog ReplaceAttr Rewrites JSON Fields?
- The runtime alone is enough: execute the file as a complete program.
Report a problem with this exampleOpens a pre-filled issue on GitHub.