← 返回 Skills 市场
samber

Golang Samber Slog

作者 Samuel Berthe · GitHub ↗ · v1.0.3 · MIT-0
cross-platform ✓ 安全检测通过
179
总下载
0
收藏
1
当前安装
3
版本数
在 OpenClaw 中安装
/install golang-samber-slog
功能描述
Structured logging extensions for Golang using samber/slog-**** packages — multi-handler pipelines (slog-multi), log sampling (slog-sampling), attribute form...
使用说明 (SKILL.md)

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.

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

Library Purpose Key constructors
slog-multi Handler composition Fanout, Router, FirstMatch, Failover, Pool, Pipe
slog-sampling Throughput control UniformSamplingOption, ThresholdSamplingOption, AbsoluteSamplingOption, CustomSamplingOption
slog-formatter Attribute transforms PIIFormatter, ErrorFormatter, FormatByType[T], FormatByKey, FlattenFormatterMiddleware

slog-multi — Handler Composition

Six composition patterns, each for a different routing need:

Pattern Behavior Latency impact
Fanout(handlers...) Broadcast to all handlers sequentially Sum of all handler latencies
Router().Add(h, predicate).Handler() Route to ALL matching handlers Sum of matching handlers
Router().Add(...).FirstMatch().Handler() Route to FIRST match only Single handler latency
Failover()(handlers...) Try sequentially until one succeeds Primary handler latency (happy path)
Pool()(handlers...) Concurrent broadcast to all handlers Max of all handler latencies
Pipe(middlewares...).Handler(sink) Middleware chain before sink Middleware 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

Strategy Behavior Best for
Uniform Drop fixed % of all records Dev/staging noise reduction
Threshold Log first N per interval, then sample at rate R Production — preserves initial visibility
Absolute Cap at N records per interval globally Hard cost control
Custom User function returns sample rate per record Level-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.

Category Packages
Cloud slog-datadog, slog-sentry, slog-loki, slog-graylog
Messaging slog-kafka, slog-fluentd, slog-logstash, slog-nats
Notification slog-slack, slog-telegram, slog-webhook
Storage slog-parquet
Bridges slog-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

Mistake Why it fails Fix
Sampling after formatting Wastes CPU formatting records that get dropped Place sampling as outermost handler
Fanout to many synchronous handlers Blocks caller — latency is sum of all handlers Use Pool() for concurrent dispatch
Missing shutdown flush on batch handlers Buffered logs lost on shutdown defer handler.Stop(ctx) (Datadog), defer lokiClient.Stop() (Loki), defer writer.Close() (Kafka)
Router without default/catch-all handler Unmatched records silently dropped Add a handler with no predicate as catch-all
AttrFromContext without HTTP middleware Context has no request attributes to extract Install slog-gin/echo/fiber/chi middleware first
Using Pipe with no middleware No-op wrapper adding per-record overhead Remove 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).

安全使用建议
This is a documentation-only skill describing how to compose samber/slog Go logging pipelines — it appears coherent and low-risk. Before using in production: (1) review and pin the actual library versions you import (the skill references v2/v3 in places), (2) provide backend credentials (Datadog, Sentry, Slack, Loki, webhook URLs) only to your application and keep them secret, (3) follow the guidance to flush/Stop batched handlers during graceful shutdown to avoid lost logs, and (4) validate PII scrubbing and sampling rules in staging so you don’t accidentally drop errors or leak sensitive data. If you want extra assurance, inspect the upstream repositories (github.com/samber/...) referenced in the docs before embedding these handlers in your codebase.
功能分析
Type: OpenClaw Skill Name: golang-samber-slog Version: 1.0.3 The skill bundle provides legitimate documentation and instructions for using the 'samber/slog' ecosystem of Go logging libraries. It includes detailed guides on handler composition, sampling strategies, and HTTP middlewares, with all references pointing to official GitHub repositories (github.com/samber). No malicious code, data exfiltration patterns, or harmful prompt injections were identified across the SKILL.md or reference files.
能力评估
Purpose & Capability
Name/description focus on samber/slog libraries and the skill only requires the Go binary and provides code examples and references — these are proportionate and expected for a Go logging guidance skill.
Instruction Scope
SKILL.md contains concrete Go code examples, pipeline patterns, and references to handler constructors and shutdown semantics; it does not instruct reading unrelated files, exfiltrating data, or using unrelated environment variables or system paths.
Install Mechanism
No install spec and no code files to execute — instruction-only skills have minimal disk/write risk. Examples reference public import paths (github.com/samber/...) rather than downloads from unknown servers.
Credentials
The skill requests no environment variables or credentials. It shows examples that mention webhooks/tokens for backends (expected) but does not require them itself.
Persistence & Privilege
always:false and no install actions. The skill does not request permanent presence or modify other skills/configs. Autonomous invocation is allowed by default but there are no other red flags that amplify risk.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install golang-samber-slog
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /golang-samber-slog 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.0.3
- Bumped skill version to 1.0.3 in metadata. - Added allowed tool: AskUserQuestion. - Fixed minor typo ("more informations" → "more information") in documentation. - No functional or behavioral changes—documentation and metadata update only.
v1.0.1
- Version updated to 1.0.1. - Added evaluation file: `evals/evals.json`. - Minor metadata update in SKILL.md (version field). - No functional or documentation changes to core skill logic.
v0.1.0
Initial release — introduces structured logging skill for Go using samber/slog-* packages. - Provides overview and usage for slog-multi, slog-sampling, and slog-formatter libraries. - Documents pipeline ordering, middleware chaining, and routing patterns. - Describes available HTTP middlewares and configuration options. - Lists supported third-party backend sinks and their constructor patterns. - Details best practices, common mistakes, and references for further exploration.
元数据
Slug golang-samber-slog
版本 1.0.3
许可证 MIT-0
累计安装 1
当前安装数 1
历史版本数 3
常见问题

Golang Samber Slog 是什么?

Structured logging extensions for Golang using samber/slog-**** packages — multi-handler pipelines (slog-multi), log sampling (slog-sampling), attribute form... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 179 次。

如何安装 Golang Samber Slog?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install golang-samber-slog」即可一键安装,无需额外配置。

Golang Samber Slog 是免费的吗?

是的,Golang Samber Slog 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

Golang Samber Slog 支持哪些平台?

Golang Samber Slog 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Golang Samber Slog?

由 Samuel Berthe(@samber)开发并维护,当前版本 v1.0.3。

💬 留言讨论