luminyra
Guides

Log handlers and sampling

Combine standard handlers with redaction and sampling to retain errors and limit repeated messages.

Format before writing

The first middleware in Chain is the outermost. The example uses FormatMiddleware with Redact to mask passwords and tokens and FormatErrors to expand error attributes. The standard-library slog.NewMultiHandler then forwards records to the text and JSON handlers. Each handler still filters by its own configured level.

sl/examples/handlers/main.go
// 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)
View on GitHub

Combine sampling rules

AnyOf keeps a record when any rule passes. LevelAtLeast admits error-level records. ThresholdSampler counts records by message in each time window. The example keeps the first two records for each other message per second. SampleMiddleware applies those rules to the handler.

sl/examples/handlers/main.go
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)
}
View on GitHub
sl/example_test.go
text := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: stable})
sampler := sl.AnyOf(
	sl.LevelAtLeast(slog.LevelError),       // never drop errors
	sl.ThresholdSampler(time.Hour, 1, nil), // otherwise keep the first record of each message
)
logger := slog.New(sl.NewSampleHandler(text, sampler))

for range 3 {
	logger.Warn("retrying")
	logger.Error("giving up")
}
Expected output
level=WARN msg=retrying
level=ERROR msg="giving up"
level=ERROR msg="giving up"
level=ERROR msg="giving up"
View on GitHub

On this page