快速上手
把脱敏、错误格式化与组合采样串接到标准日志处理器。
运行日志示例
使用 Go 1.27 或更高版本,安装 sl 后把完整示例保存到 main.go 并运行 go run .。也可在 sl 源码目录执行 go run ./examples/handlers。
go get github.com/luminyra/sl// Command handlers combines sl with the standard library: it redacts secrets,
// formats errors, samples without ever dropping errors, and fans out to
// several outputs with slog.NewMultiHandler.
package main
import (
"errors"
"log/slog"
"os"
"time"
"github.com/luminyra/sl"
)
// dropTime removes the time attribute to keep the example output stable.
func dropTime(_ []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
}
func main() {
// Every record goes to a text handler; errors also go to a JSON handler,
// for example one that feeds an alerting system. The standard
// slog.NewMultiHandler (Go 1.26+) does the fan-out.
text := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: dropTime})
alerts := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelError, ReplaceAttr: dropTime})
// Samplers are plain functions and compose: keep every error, and keep
// only the first two records of any other message per second.
sampler := sl.AnyOf(
sl.LevelAtLeast(slog.LevelError),
sl.ThresholdSampler(time.Second, 2, nil),
)
// The first middleware passed to Chain is the outermost: redact and
// format first, then sample, then fan out.
handler := sl.Chain(slog.NewMultiHandler(text, alerts),
sl.FormatMiddleware(sl.Redact("password", "token"), sl.FormatErrors()),
sl.SampleMiddleware(sampler),
)
logger := slog.New(handler)
logger.Info("user logged in", "user", "alice", "password", "hunter2", slog.Group("auth", "token", "abc123"))
logger.Error("query failed", "err", errors.New("connection refused"))
for i := range 5 {
logger.Warn("retrying", "attempt", i+1)
}
}检查脱敏与采样
Chain 先应用格式化再应用采样。登录记录中的密码和令牌被遮盖,错误保留结构化信息。对相同的重试消息,采样器在时间窗口内只保留有限条。错误级别记录仍保留并进入 JSON 输出。
text := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: stable})
logger := slog.New(sl.Chain(text,
sl.FormatMiddleware(sl.Redact("password"), sl.FormatErrors()),
))
logger.Info("login", "user", "alice", "password", "hunter2")
logger.Error("query failed", "err", errors.New("connection refused"))level=INFO msg=login user=alice password=*******
level=ERROR msg="query failed" err.message="connection refused" err.type=*errors.errorString需要调整采样规则时,继续阅读 保留错误并限制重复消息。