Now liveThe Skillselion MCP - thousands of ranked skills, loaded into your agent mid-task. No install.Get it →
samber avatar

Golang Samber Slog

  • 33.1k installs
  • 2.8k repo stars
  • Updated July 27, 2026
  • samber/cc-skills-golang

samber/slog-**** is a collection of composable Go handler packages that extend slog with multi-handler pipelines, sampling, formatting, and backend routing.

About

samber/slog-**** is a collection of 20+ composable slog.Handler packages for Go 1.21+ implementing a canonical logging pipeline. Developers use it to build production logging architectures where records flow through sampling (to reduce noise), formatters (to strip PII), and routers (to send errors to Sentry while info goes to Loki). It matters because sampling before formatting saves CPU, and routing separates concerns without duplicating handlers.

  • 20+ composable handler packages for structured logging
  • Canonical pipeline: sampling - formatting - routing - sinks
  • Integrates with Datadog, Sentry, Loki, and 15+ backends

Golang Samber Slog by the numbers

  • 33,144 all-time installs (skills.sh)
  • +434 installs in the week ending Jul 28, 2026 (Skillselion tracking)
  • Ranked #24 of 4,386 Backend & APIs skills by installs in the Skillselion catalog
  • Security screen: LOW risk (skills.sh audit)
  • Data as of Jul 28, 2026 (Skillselion catalog sync)
At a glance

golang-samber-slog capabilities & compatibility

Works with
datadog · sentry · kafka · slack
Use cases
debugging
From the docs

What golang-samber-slog says it does

Six composition patterns, each for a different routing need
SKILL.md
npx skills add https://github.com/samber/cc-skills-golang --skill golang-samber-slog

Add your badge

Show developers this skill is listed on Skillselion. Paste this into your README.

Listed on Skillselion
Installs33.1k
repo stars2.8k
Security audit3 / 3 scanners passed
Last updatedJuly 27, 2026
Repositorysamber/cc-skills-golang

What it does

Building multi-sink logging pipelines in Go with sampling, PII scrubbing, and backend routing (Datadog, Sentry, Loki) for production observability.

Who is it for?

Production logging architectures; multi-sink pipelines; PII scrubbing; throughput control; APM backend integration

Skip if: CLI tools with stdout-only logging or services using zap or zerolog instead of slog ecosystems.

When should I use this skill?

Using Go 1.21+ with slog; building multi-sink logging; need sampling for high-throughput systems; must route different log levels to different backends

What you get

Ordered slog handler chain, masked PII fields, Sentry-routed errors, and sampled log output at configured rates.

  • ordered slog handler pipeline
  • pii masking rules
  • sentry error routing

By the numbers

  • pipeline-ordering eval configures 10% log sampling rate
  • Combines 3 libraries: slog-multi, slog-sampling, and slog-formatter

Files

SKILL.mdMarkdownGitHub ↗

Persona: You are a Go logging architect. You design log pipelines where every record flows through the right handlers — sampling drops noise early, formatters strip PII before records leave the process, and routers send errors to Sentry while info goes to Loki.

samber/slog-\\\\ — Structured Logging Pipeline for Go

20+ composable slog.Handler packages for Go 1.21+. Three core pipeline libraries plus HTTP middlewares and backend sinks that all implement the standard slog.Handler interface.

Official resources:

This skill is not exhaustive. Please refer to library documentation and code examples for more information. Context7 can help as a discoverability platform. For Go package docs, versions, symbols, and known vulnerabilities, → See samber/cc-skills-golang@golang-pkg-go-dev skill.

The Pipeline Model

Every samber/slog pipeline follows a canonical ordering. Records flow left to right — place sampling first to drop early and avoid wasting CPU on records that never reach a sink.

record → [Sampling] → [Pipe: trace/PII] → [Router] → [Sinks]

Order matters: sampling before formatting saves CPU. Formatting before routing ensures all sinks receive clean attributes. Reversing this wastes work on records that get dropped.

Core Libraries

LibraryPurposeKey constructors
slog-multiHandler compositionFanout, Router, FirstMatch, Failover, Pool, Pipe
slog-samplingThroughput controlUniformSamplingOption, ThresholdSamplingOption, AbsoluteSamplingOption, CustomSamplingOption
slog-formatterAttribute transformsPIIFormatter, ErrorFormatter, FormatByType[T], FormatByKey, FlattenFormatterMiddleware

slog-multi — Handler Composition

Six composition patterns, each for a different routing need:

PatternBehaviorLatency impact
Fanout(handlers...)Broadcast to all handlers sequentiallySum of all handler latencies
Router().Add(h, predicate).Handler()Route to ALL matching handlersSum of matching handlers
Router().Add(...).FirstMatch().Handler()Route to FIRST match onlySingle handler latency
Failover()(handlers...)Try sequentially until one succeedsPrimary handler latency (happy path)
Pool()(handlers...)Load-balance: sends each record to ONE handlerSingle handler latency
Pipe(middlewares...).Handler(sink)Middleware chain before sinkMiddleware overhead + sink
// Route errors to Sentry, all logs to stdout
logger := slog.New(
    slogmulti.Router().
        Add(sentryHandler, slogmulti.LevelIs(slog.LevelError)).
        Add(slog.NewJSONHandler(os.Stdout, nil)).
        Handler(),
)

Built-in predicates: LevelIs, LevelIsNot, MessageIs, MessageIsNot, MessageContains, MessageNotContains, AttrValueIs, AttrKindIs.

For full code examples of every pattern, see Pipeline Patterns.

slog-sampling — Throughput Control

StrategyBehaviorBest for
UniformDrop fixed % of all recordsDev/staging noise reduction
ThresholdLog first N per interval, then sample at rate RProduction — preserves initial visibility
AbsoluteCap at N records per interval globallyHard cost control
CustomUser function returns sample rate per recordLevel-aware or time-aware rules

Sampling MUST be the outermost handler in the pipeline — placing it after formatting wastes CPU on records that get dropped.

// Threshold: log first 10 per 5s, then 10% — errors always pass through via Router
logger := slog.New(
    slogmulti.
        Pipe(slogsampling.ThresholdSamplingOption{
            Tick: 5 * time.Second, Threshold: 10, Rate: 0.1,
        }.NewMiddleware()).
        Handler(innerHandler),
)

Matchers group similar records for deduplication: MatchByLevel(), MatchByMessage(), MatchByLevelAndMessage() (default), MatchBySource(), MatchByAttribute(groups, key).

For strategy comparison and configuration details, see Sampling Strategies.

slog-formatter — Attribute Transformation

Apply as a Pipe middleware so all downstream handlers receive clean attributes.

logger := slog.New(
    slogmulti.Pipe(slogformatter.NewFormatterMiddleware(
        slogformatter.PIIFormatter("user"),          // mask PII fields
        slogformatter.ErrorFormatter("error"),       // structured error info
        slogformatter.IPAddressFormatter("client"),  // mask IP addresses
    )).Handler(slog.NewJSONHandler(os.Stdout, nil)),
)

Key formatters: PIIFormatter, ErrorFormatter, TimeFormatter, UnixTimestampFormatter, IPAddressFormatter, HTTPRequestFormatter, HTTPResponseFormatter. Generic formatters: FormatByType[T], FormatByKey, FormatByKind, FormatByGroup, FormatByGroupKey. Flatten nested attributes with FlattenFormatterMiddleware.

HTTP Middlewares

Consistent pattern across frameworks: router.Use(slogXXX.New(logger)).

Available: slog-gin, slog-echo, slog-fiber, slog-chi, slog-http (net/http).

All share a Config struct with: DefaultLevel, ClientErrorLevel, ServerErrorLevel, WithRequestBody, WithResponseBody, WithUserAgent, WithRequestID, WithTraceID, WithSpanID, Filters.

// Gin with filters — skip health checks
router.Use(sloggin.NewWithConfig(logger, sloggin.Config{
    DefaultLevel:     slog.LevelInfo,
    ClientErrorLevel: slog.LevelWarn,
    ServerErrorLevel: slog.LevelError,
    WithRequestBody:  true,
    Filters: []sloggin.Filter{
        sloggin.IgnorePath("/health", "/metrics"),
    },
}))

For framework-specific setup, see HTTP Middlewares.

Backend Sinks

All follow the Option{}.NewXxxHandler() constructor pattern.

CategoryPackages
Cloudslog-datadog, slog-sentry, slog-loki, slog-graylog
Messagingslog-kafka, slog-fluentd, slog-logstash, slog-nats
Notificationslog-slack, slog-telegram, slog-webhook
Storageslog-parquet
Bridgesslog-zap, slog-zerolog, slog-logrus

Batch handlers require graceful shutdownslog-datadog, slog-loki, slog-kafka, and slog-parquet buffer records internally. Flush on shutdown (e.g., handler.Stop(ctx) for Datadog, lokiClient.Stop() for Loki, writer.Close() for Kafka) or buffered logs are lost.

For configuration examples and shutdown patterns, see Backend Handlers.

Common Mistakes

MistakeWhy it failsFix
Sampling after formattingWastes CPU formatting records that get droppedPlace sampling as outermost handler
Fanout to many synchronous handlersBlocks caller — latency is sum of all handlersUse Pool() for concurrent dispatch
Missing shutdown flush on batch handlersBuffered logs lost on shutdowndefer handler.Stop(ctx) (Datadog), defer lokiClient.Stop() (Loki), defer writer.Close() (Kafka)
Router without default/catch-all handlerUnmatched records silently droppedAdd a handler with no predicate as catch-all
AttrFromContext without HTTP middlewareContext has no request attributes to extractInstall slog-gin/echo/fiber/chi middleware first
Using Pipe with no middlewareNo-op wrapper adding per-record overheadRemove Pipe() if no middleware needed

Performance Warnings

  • Fanout latency = sum of all handler latencies (sequential). With 5 handlers at 10ms each, every log call costs 50ms. Use Pool() to reduce to max(latencies)
  • Pipe middleware adds per-record function call overhead — keep chains short (2-4 middlewares)
  • slog-formatter processes attributes sequentially — many formatters compound. For hot-path attribute formatting, prefer implementing slog.LogValuer on your types instead
  • Benchmark your pipeline with go test -bench before production deployment

Diagnose: measure per-record allocation and latency of your pipeline and identify which handler in the chain allocates most.

Best Practices

1. Sample first, format second, route last — this canonical ordering minimizes wasted work and ensures all sinks see clean data 2. Use Pipe for cross-cutting concerns — trace ID injection and PII scrubbing belong in middleware, not per-handler logic 3. Test pipelines with `slogmulti.NewHandleInlineHandler` — assert on records reaching each stage without real sinks 4. Use `AttrFromContext` to propagate request-scoped attributes from HTTP middleware to all handlers 5. Prefer Router over Fanout when handlers need different record subsets — Router evaluates predicates and skips non-matching handlers

Cross-References

  • → See samber/cc-skills-golang@golang-observability skill for slog fundamentals (levels, context, handler setup, migration)
  • → See samber/cc-skills-golang@golang-error-handling skill for the log-or-return rule
  • → See samber/cc-skills-golang@golang-security skill for PII handling in logs
  • → See samber/cc-skills-golang@golang-samber-oops skill for structured error context with samber/oops

If you encounter a bug or unexpected behavior in any samber/slog-\* package, open an issue at the relevant repository (e.g., slog-multi/issues, slog-sampling/issues).

Related skills

How it compares

Use golang-samber-slog for multi-handler slog stacks; use basic slog skills when a single JSON handler without sampling or PII rules is enough.

FAQ

Why put sampling first in the pipeline?

Sampling drops records early before formatting wastes CPU. If you format then sample, you wasted work formatting records that get dropped. Order matters: sampling - formatting - routing - sinks.

Do I need all the packages or just a few?

Start with slog-multi (composition), slog-sampling (throughput control), and slog-formatter (PII). Add backend sinks (slog-datadog, slog-sentry, slog-loki) only for those destinations.

Is Golang Samber Slog safe to install?

skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.

Backend & APIsmonitoringinfra

This week in AI coding

Five minutes, every Monday - the tools, releases and tactics for developers.

unsubscribe anytime.