Xpersona
G

golang-samber-slog

CLAWHUB · Unverified

Structured logging extensions for Golang using samber/slog-**** packages — multi-handler pipelines (slog-multi), log sampling (slog-sampling), attribute formatting (slog-formatter), HTTP middleware (slog-fiber, slog-gin, slog-chi, slog-echo), and backend routing (slog-datadog, slog-sentry, slog-loki, slog-syslog, slog-logstash, slog-graylog...). Apply when using or adopting slog, or when the codebase already imports any github.com/samber/slog-* package. Skill: golang-samber-slog Owner: samber Summary: Structured logging extensions for Golang using samber/slog-**** packages — multi-handler pipelines (slog-multi), log sampling (slog-sampling), attribute formatting (slog-formatter), HTTP middleware (slog-fiber, slog-gin, slog-chi, slog-echo), and backend routing (slog-datadog, slog-sentry, slog-loki, slog-syslog, slog-logstash, slog-graylog...). Apply when using or ado

62
Rank
84
Safety
1.3k
Downloads

About

What it does, and when to use it.

Capability contract not published. No trust telemetry is available yet. 1.3K downloads reported by the source. Last updated 10/10/2026.

Avoid when

  • Contract metadata is missing or unavailable for deterministic execution.

Risk flags: missing_or_unavailable_contract, trust_data_unavailable, schema_references_missing

Install and run

Setup complexity: low.

clawhub skill install s173arkhs3131fq5jf769qq75583hdgt:golang-samber-slog
  1. Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.
  2. Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data.

Contract: missing

curl -s "https://www.xpersona.co/api/v1/agents/clawhub-samber-golang-samber-slog/snapshot"

Run-check

$0.02 USD

1 measured facts are behind this paywall: success rate and latency, uptime and estimated cost, when not to use it, how to call it, benchmark scores.

Agents pay $0.02 in USDC. A card payment is $0.50, the smallest a card allows.

Documentation

CLAWHUB

144,512 characters of source documentation, loaded on request.

Extracted files

5 files captured from the source.

SKILL.md

---
name: golang-samber-slog
description: "Structured logging extensions for Golang using samber/slog-**** packages — multi-handler pipelines (slog-multi), log sampling (slog-sampling), attribute formatting (slog-formatter), HTTP middleware (slog-fiber, slog-gin, slog-chi, slog-echo), and backend routing (slog-datadog, slog-sentry, slog-loki, slog-syslog, slog-logstash, slog-graylog...). Apply when using or adopting slog, or when the codebase already imports any github.com/samber/slog-* package."
user-invocable: true
license: MIT
compatibility: Designed for Claude Code, Codex or similar harness, and for projects using Golang.
metadata:
  author: samber
  version: "1.1.0"
  openclaw:
    emoji: "🪵"
    homepage: https://github.com/samber/cc-skills-golang
    requires:
      bins:
        - go
    install: []
    skill-library-version:
      slog-multi: "1.8.0"
      slog-sampling: "1.6.0"
      slog-formatter: "1.3.0"
      slog-fiber: "1.22.1"
      slog-gin: "1.21.0"
      slog-chi: "1.19.0"
      slog-echo: "1.21.0"
      slog-http: "1.12.0"
      slog-betterstack: "1.4.4"
      slog-channel: "1.4.4"
      slog-datadog: "2.10.4"
      slog-sentry: "2.10.3"
      slog-loki: "3.7.2"
      slog-syslog: "2.5.4"
      slog-logstash: "2.6.4"
      slog-graylog: "2.7.5"
      slog-fluentd: "2.5.4"
      slog-kafka: "2.6.5"
      slog-logrus: "2.5.4"
      slog-zap: "2.6.4"
      slog-zerolog: "2.9.2"
      slog-slack: "2.7.5"
      slog-telegram: "2.4.4"
      slog-webhook: "2.8.4"
      slog-mattermost: "2.5.4"
      slog-microsoft-teams: "2.7.4"
      slog-nats: "0.4.5"
      slog-otel: "0.1.0"
      slog-parquet: "2.5.2"
      slog-quickwit: "0.3.4"
      slog-rollbar: "2.7.4"
      slog-mock: "0.1.0"
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent WebFetch mcp__context7__resolve-library-id mcp__context7__query-docs AskUserQuestion Bash(godig:*) Bash(gopls:*) LSP mcp__gopls__*
paths:
  - "**/*.go"
---

**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:**

- [github.com/samber/slog-multi](https://github.com/samber/slog-multi) — handler composition
- [github.com/samber/slog-sampling](https://github.com/samber/slog-sampling) — throughput control
- [github.com/samber/slog-formatter](https://github.com/samber/slog-formatter) — attribute transformation

This skill is not exhaustive. Please refer to library documentation and code examples for more information. For Go package docs, symbols, versions, importers, and known vulnerabilities, → 

_meta.json

{
  "ownerId": "kn72rhnkwjfeex9wr1n7y24qa983cjn3",
  "slug": "golang-samber-slog",
  "version": "1.1.0",
  "publishedAt": 1787441511360
}

references/backend-handlers.md

# Backend Handlers

All backend handlers implement `slog.Handler` and follow the `Option{}.NewXxxHandler()` constructor pattern.

## Common Option Fields

Every handler's `Option` struct includes:

| Field | Purpose |
| --- | --- |
| `Level` | Minimum log level (default: `slog.LevelDebug`) |
| `AddSource` | Include source file/line in log output |
| `ReplaceAttr` | Callback to modify attributes before emission |
| `Converter` | Custom payload builder for the target format |
| `AttrFromContext` | Slice of functions extracting attributes from `context.Context` |

## Cloud Backends

### Datadog — `slog-datadog`

```go
import slogdatadog "github.com/samber/slog-datadog/v2"

handler := slogdatadog.Option{
    Level: slog.LevelInfo,
    // Service, Source, Hostname, Tags configured via Datadog client
}.NewDatadogHandler()
defer handler.(interface{ Stop(context.Context) error }).Stop(context.Background()) // REQUIRED: flush buffered logs
```

**Batch mode** is the default — logs are buffered and sent periodically (default 5s). Call `Stop(ctx)` on shutdown or buffered logs are lost. The handler also exposes `Flush(ctx)` for mid-lifecycle flushes. For synchronous delivery, check the Option configuration.

### Sentry — `slog-sentry`

```go
import slogsentry "github.com/samber/slog-sentry/v2"

handler := slogsentry.Option{
    Level:   slog.LevelWarn,
    Hub:     sentry.CurrentHub(),
    AddSource: true,
}.NewSentryHandler()

// Flush on shutdown
defer sentry.Flush(2 * time.Second)
```

**Recognized attributes:** `error` (any error type), `request` (\*http.Request), `dist`, `environment`, `release`, `server_name`, `transaction`. Use `slog.Group("tags", ...)` for Sentry tags and `slog.Group("user", ...)` for user context.

**Error keys:** Global `ErrorKeys = []string{"error", "err"}` — attributes with these keys are treated as error objects.

### Loki — `slog-loki`

```go
import slogloki "github.com/samber/slog-loki/v3"

lokiClient, _ := loki.New(lokiCfg)
defer lokiClient.Stop() // REQUIRED: flush buffered logs

handler := slogloki.Option{
    Level:  slog.LevelDebug,
    Client: lokiClient,
}.NewLokiHandler()
```

**Labels vs metadata:** By default, attributes are sent as Loki labels. For high-cardinality data (request IDs, trace IDs), enable `HandleRecordsWithMetadata: true` to send as structured metadata instead — this avoids label explosion that degrades Loki performance.

### Graylog — `slog-graylog`

```go
import sloggraylog "github.com/samber/slog-graylog/v2"

gelfWriter, _ := gelf.NewWriter("localhost:12201")
handler := sloggraylog.Option{
    Level:  slog.LevelDebug,
    Writer: gelfWriter,
}.NewGraylogHandler()
```

Uses GELF (Graylog Extended Log Format) over UDP.

## Messaging Backends

### Kafka — `slog-kafka`

```go
import slogkafka "github.com/samber/slog-kafka/v2"

writer := &kafka.Writer{
    Addr:  kafka.TCP("localhost:9092"),
    Topic: "logs",
    Async: true, // non-blocking writes
}
handler := slogkafka.Option{
    Level:       slog.Le

references/http-middlewares.md

# HTTP Middlewares

All samber/slog HTTP middlewares share a consistent pattern and configuration structure.

## Shared Config Fields

Every middleware provides a `Config` struct with these common fields:

| Field | Type | Default | Purpose |
| --- | --- | --- | --- |
| `DefaultLevel` | `slog.Level` | `slog.LevelInfo` | Log level for 2xx/3xx responses |
| `ClientErrorLevel` | `slog.Level` | `slog.LevelWarn` | Log level for 4xx responses |
| `ServerErrorLevel` | `slog.Level` | `slog.LevelError` | Log level for 5xx responses |
| `WithUserAgent` | `bool` | `false` | Include `User-Agent` header |
| `WithRequestID` | `bool` | `false` | Include request ID |
| `WithRequestBody` | `bool` | `false` | Include request body (capped) |
| `WithResponseBody` | `bool` | `false` | Include response body (capped) |
| `WithRequestHeader` | `bool` | `false` | Include request headers |
| `WithResponseHeader` | `bool` | `false` | Include response headers |
| `WithSpanID` | `bool` | `false` | Include OpenTelemetry span ID |
| `WithTraceID` | `bool` | `false` | Include OpenTelemetry trace ID |
| `WithClientIP` | `bool` | `false` | Include client IP address |
| `Filters` | `[]Filter` | `nil` | Request filter functions |

**Global configuration variables** (set before creating middleware):

- `RequestBodyMaxSize` / `ResponseBodyMaxSize` — default 64KB each
- `HiddenRequestHeaders` / `HiddenResponseHeaders` — headers to redact
- `TraceIDKey` / `SpanIDKey` — context key names for OpenTelemetry

## Default Log Fields

All middlewares emit these fields by default: `method`, `path`, `status`, `latency`, `request-length`, `response-length`.

## Gin — `slog-gin`

```go
import sloggin "github.com/samber/slog-gin"

// Simple
router := gin.New()
router.Use(sloggin.New(logger))

// With config
router.Use(sloggin.NewWithConfig(logger, sloggin.Config{
    DefaultLevel:     slog.LevelInfo,
    ClientErrorLevel: slog.LevelWarn,
    ServerErrorLevel: slog.LevelError,
    WithRequestBody:  true,
    WithUserAgent:    true,
    Filters: []sloggin.Filter{
        sloggin.IgnorePath("/health", "/metrics"),
        sloggin.IgnorePathPrefix("/static"),
    },
}))

// Custom attributes per request
router.GET("/api/users", func(c *gin.Context) {
    sloggin.AddCustomAttributes(c, slog.String("user_id", userID))
    c.JSON(200, users)
})
```

## Echo — `slog-echo`

```go
import slogecho "github.com/samber/slog-echo"

e := echo.New()
e.Use(slogecho.New(logger))

// With config
e.Use(slogecho.NewWithConfig(logger, slogecho.Config{
    DefaultLevel:     slog.LevelInfo,
    ClientErrorLevel: slog.LevelWarn,
    ServerErrorLevel: slog.LevelError,
    WithRequestBody:  true,
    Filters: []slogecho.Filter{
        slogecho.IgnoreStatus(404),
        slogecho.IgnorePath("/health"),
    },
}))

// Custom attributes
e.GET("/api/users", func(c echo.Context) error {
    slogecho.AddCustomAttributes(c, slog.String("user_id", userID))
    return c.JSON(200, users)
})
```

## Fiber — `slog-fiber`

```go
import 

references/pipeline-patterns.md

# Pipeline Patterns

Complete code examples for every `slog-multi` composition pattern.

## Fanout — Broadcast to All

Sends every record to every handler sequentially. Latency = sum of all handler latencies.

```go
import slogmulti "github.com/samber/slog-multi"

logger := slog.New(
    slogmulti.Fanout(
        slog.NewJSONHandler(os.Stdout, nil),           // stdout
        slog.NewTextHandler(logFile, nil),              // file
        slogsentry.Option{Level: slog.LevelError}.NewSentryHandler(), // Sentry
    ),
)
```

**When to use:** Every destination must receive every record (audit logs, compliance). **When NOT to use:** Handlers have different record needs (use Router) or high latency (use Pool).

## Router — Predicate-Based Routing

Routes records to ALL handlers whose predicate matches. Unmatched records go nowhere unless a default handler is added.

```go
logger := slog.New(
    slogmulti.Router().
        Add(sentryHandler, slogmulti.LevelIs(slog.LevelError)).
        Add(slackHandler, slogmulti.LevelIs(slog.LevelWarn)).
        Add(lokiHandler, slogmulti.LevelIs(slog.LevelInfo, slog.LevelDebug)).
        Add(slog.NewJSONHandler(os.Stdout, nil)). // catch-all: no predicate
        Handler(),
)
```

**Built-in predicates:**

```go
slogmulti.LevelIs(slog.LevelError)             // match specific levels
slogmulti.LevelIsNot(slog.LevelDebug)          // exclude levels
slogmulti.MessageIs("payment processed")       // exact message match
slogmulti.MessageIsNot("healthcheck")          // exclude exact message
slogmulti.MessageContains("timeout")           // partial message match
slogmulti.MessageNotContains("debug")          // exclude partial message
slogmulti.AttrValueIs("module", "billing")     // match attribute value
slogmulti.AttrKindIs(slog.KindString)          // match attribute kind
```

**Custom predicate:**

```go
func recordMatchRegion(region string) func(ctx context.Context, r slog.Record) bool {
    return func(ctx context.Context, r slog.Record) bool {
        match := false
        r.Attrs(func(attr slog.Attr) bool {
            if attr.Key == "region" && attr.Value.String() == region {
                match = true
                return false
            }
            return true
        })
        return match
    }
}

logger := slog.New(
    slogmulti.Router().
        Add(slackUS, recordMatchRegion("us")).
        Add(slackEU, recordMatchRegion("eu")).
        Handler(),
)
```

**Warning:** Records matching no predicate are silently dropped. Always add a catch-all handler (no predicate) unless you intentionally want to discard unmatched records.

## FirstMatch — Short-Circuit Routing

Like Router but stops at the first matching handler. Each record goes to exactly one destination.

```go
logger := slog.New(
    slogmulti.Router().
        Add(queryHandler, matchQueryLogs).     // priority 1
        Add(requestHandler, matchRequestLogs). // priority 2
        Add(defaultHandler).                   // fallback
        F

Sponsored

Ads related to golang-samber-slog and adjacent AI workflows.