CodeSampleX

サンプル

go.uber.org/zap v1.28.0: Configure rate-limited log sampling using zapcore.NewSamplerWithOptions and verify first N entries and subsequent periodic sampling

検証済みサンプル — golang go.uber.org/zap v1.28.0: Configure rate-limited log sampling using zapcore.NewSamplerWithOptions and verify first N entries and subsequent…

sha256:39bfd747137e0de209238baafbade6b9cdb2a12b5784ceca9a9f7804934acf32

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 go linux x64 go go go

検証実行環境

環境 コントラクト ステージ 実行日
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-28

ケース

HOW
ゴール
Configure rate-limited log sampling using zapcore.NewSamplerWithOptions and verify first N entries and subsequent periodic sampling
パッケージ
シンボル
  • zapcore.NewSamplerWithOptions
  • zapcore.SamplerHook
  • zapcore.SamplerWithOptions
環境
go
作成日
2026-08-28T06:51:09Z

コントラクト

  1. zapcore.NewSamplerWithOptions creates a core that logs the first N entries with the same level and message each tick interval
  2. subsequent entries with the same level and message within the interval are sampled every Mth entry when thereafter is positive
  3. zapcore.SamplerHook receives sampling decisions indicating whether an entry was sampled via zapcore.LogSampled or dropped via zapcore.LogDropped
  4. different log messages and levels maintain independent sampling counters and quotas
  5. setting thereafter to zero drops all entries following the initial N occurrences within the tick interval

ファイル

  • NOTES.md
  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • sampler_test.go
  • spec.json

ソースアーティファクトをダウンロード (tar.gz)

ソース

NOTES.md
# zap Log Sampling with zapcore.NewSamplerWithOptions

## Prior Findings
A search for existing solutions on `go.uber.org/zap` returned compatible samples:
- `sha256:b4d93830bc0e5b11f48fcdf14a96fdb8c2a50cbdf593162924b6eef58f61301d` (Runtime dynamic level switching with `zap.AtomicLevel`)
- `sha256:04fc0c107cbd38bfee7ae0fc1da9d91546055682997e3eee211708b9a7b77aea` (In-memory log capture and development vs production `DPanic` behavior)
- `sha256:46df4736d445e122bed613d66d9074610072b234cffa56ec4013cd41d2affee5` (`zap.RegisterSink` custom URL scheme registration and error handling)

This sample tests another core capability in `go.uber.org/zap`: rate-limited log sampling using `zapcore.NewSamplerWithOptions` and decision tracking via `zapcore.SamplerHook`.

## Pinned Release
- `go.uber.org/zap` pinned to `v1.28.0` via `go.mod` and `go.sum`.

## Observed Behaviour
1. `zapcore.NewSamplerWithOptions(core, tick, first, thereafter, opts...)` wraps an existing `zapcore.Core` to rate-limit log throughput. Within each tick interval, the first `first` entries sharing the same log level and message are emitted as-is.
2. Subsequent log entries with the same level and message within the interval are sampled every `thereafter` entries (dropping intermediate occurrences).
3. When `thereafter` is set to `0`, all entries beyond the initial `first` occurrences in that tick interval are dropped.
4. `zapcore.SamplerHook` registers a callback function `func(entry zapcore.Entry, dec zapcore.SamplingDecision)` that executes for every incoming entry, reporting whether the entry was sampled (`dec&zapcore.LogSampled != 0`) or dropped (`dec&zapcore.LogDropped != 0`).
5. Sampling counters are isolated per `(Level, Message)` pair; distinct messages or different log levels do not exhaust each other's sampling quotas.
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: Configure rate-limited log sampling using zapcore.NewSamplerWithOptions and verify first N entries and subsequent periodic sampling
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.uber.org/zap@v1.28.0
Demonstrate these symbols/APIs:
  - zapcore.NewSamplerWithOptions
  - zapcore.SamplerHook
  - zapcore.SamplerWithOptions

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:e51f303b435a3c21aeefb38fcb792e249db9edae2a3833d700c472e102c82c07","contract":["zapcore.NewSamplerWithOptions creates a core that logs the first N entries with the same level and message each tick interval","subsequent entries with the same level and message within the interval are sampled every Mth entry when thereafter is positive","zapcore.SamplerHook receives sampling decisions indicating whether an entry was sampled via zapcore.LogSampled or dropped via zapcore.LogDropped","different log messages and levels maintain independent sampling counters and quotas","setting thereafter to zero drops all entries following the initial N occurrences within the tick interval"],"goal":"Configure rate-limited log sampling using zapcore.NewSamplerWithOptions and verify first N entries and subsequent periodic sampling","kind":"HOW","packages":["pkg:golang/go.uber.org/zap@v1.28.0"],"schemaVersion":1,"symbols":["zapcore.NewSamplerWithOptions","zapcore.SamplerHook","zapcore.SamplerWithOptions"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/go.uber.org/zap@v1.28.0"],"schemaVersion":1,"subject":"pkg:golang/go.uber.org/zap@v1.28.0","symbols":["zapcore.NewSamplerWithOptions","zapcore.SamplerHook","zapcore.SamplerWithOptions"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.0

require go.uber.org/zap v1.28.0

require go.uber.org/multierr v1.10.0 // indirect
go.sum
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
sampler_test.go
package sample

import (
	"bytes"
	"encoding/json"
	"strings"
	"sync/atomic"
	"testing"
	"time"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

type syncer struct {
	buf bytes.Buffer
}

func (s *syncer) Write(p []byte) (n int, err error) {
	return s.buf.Write(p)
}

func (s *syncer) Sync() error {
	return nil
}

func (s *syncer) String() string {
	return s.buf.String()
}

func (s *syncer) Reset() {
	s.buf.Reset()
}

func (s *syncer) Lines() []string {
	raw := strings.TrimSpace(s.buf.String())
	if raw == "" {
		return nil
	}
	return strings.Split(raw, "\n")
}

func TestSamplerFirstNAndThereafterSampling(t *testing.T) {
	sink := &syncer{}
	encCfg := zapcore.EncoderConfig{
		MessageKey:     "msg",
		LevelKey:       "level",
		EncodeLevel:    zapcore.LowercaseLevelEncoder,
		EncodeDuration: zapcore.StringDurationEncoder,
	}
	encoder := zapcore.NewJSONEncoder(encCfg)
	baseCore := zapcore.NewCore(encoder, sink, zapcore.DebugLevel)

	var sampledCount int64
	var droppedCount int64

	hook := zapcore.SamplerHook(func(entry zapcore.Entry, dec zapcore.SamplingDecision) {
		if dec&zapcore.LogSampled != 0 {
			atomic.AddInt64(&sampledCount, 1)
		}
		if dec&zapcore.LogDropped != 0 {
			atomic.AddInt64(&droppedCount, 1)
		}
	})

	// Sample: 1s interval, first 3 allowed, then every 2nd allowed (thereafter=2)
	samplerCore := zapcore.NewSamplerWithOptions(baseCore, time.Second, 3, 2, hook)
	logger := zap.New(samplerCore)

	// Emit 7 log entries with the same level and message
	for i := 1; i <= 7; i++ {
		logger.Info("repeated message", zap.Int("seq", i))
	}

	// Expected:
	// 1: Sampled (first 1)
	// 2: Sampled (first 2)
	// 3: Sampled (first 3)
	// 4: Dropped (thereafter counter 1)
	// 5: Sampled (thereafter counter 2 -> emitted)
	// 6: Dropped (thereafter counter 1)
	// 7: Sampled (thereafter counter 2 -> emitted)
	// Total sampled: 5 (seq 1, 2, 3, 5, 7)
	// Total dropped: 2 (seq 4, 6)

	lines := sink.Lines()
	if len(lines) != 5 {
		t.Fatalf("expected 5 lines in sink, got %d. Output:\n%s", len(lines), sink.String())
	}

	if atomic.LoadInt64(&sampledCount) != 5 {
		t.Fatalf("expected 5 sampled entries in hook, got %d", sampledCount)
	}
	if atomic.LoadInt64(&droppedCount) != 2 {
		t.Fatalf("expected 2 dropped entries in hook, got %d", droppedCount)
	}

	var expectedSeqs = []int{1, 2, 3, 5, 7}
	for idx, line := range lines {
		var entry map[string]interface{}
		if err := json.Unmarshal([]byte(line), &entry); err != nil {
			t.Fatalf("failed to parse JSON line %d: %v", idx, err)
		}
		seq := int(entry["seq"].(float64))
		if seq != expectedSeqs[idx] {
			t.Fatalf("at line %d expected seq %d, got %d", idx, expectedSeqs[idx], seq)
		}
	}
}

func TestSamplerMessageAndLevelIsolation(t *testing.T) {
	sink := &syncer{}
	encCfg := zapcore.EncoderConfig{
		MessageKey:  "msg",
		LevelKey:    "level",
		EncodeLevel: zapcore.LowercaseLevelEncoder,
	}
	baseCore := zapcore.NewCore(zapcore.NewJSONEncoder(encCfg), sink, zapcore.DebugLevel)

	// First 1 allowed, thereafter every 1000th (effectively dropped)
	samplerCore := zapcore.NewSamplerWithOptions(baseCore, time.Second, 1, 1000)
	logger := zap.New(samplerCore)

	// Emit msg-A twice (first emitted, second dropped)
	logger.Info("msg-A")
	logger.Info("msg-A")

	// Emit msg-B twice (first emitted, second dropped - independent of msg-A)
	logger.Info("msg-B")
	logger.Info("msg-B")

	// Emit msg-A at WarnLevel (first warn emitted - independent level)
	logger.Warn("msg-A")
	logger.Warn("msg-A")

	lines := sink.Lines()
	if len(lines) != 3 {
		t.Fatalf("expected 3 lines (1 for info msg-A, 1 for info msg-B, 1 for warn msg-A), got %d: %s", len(lines), sink.String())
	}
}

func TestSamplerThereafterZeroSuppression(t *testing.T) {
	sink := &syncer{}
	encCfg := zapcore.EncoderConfig{
		MessageKey:  "msg",
		LevelKey:    "level",
		EncodeLevel: zapcore.LowercaseLevelEncoder,
	}
	baseCore := zapcore.NewCore(zapcore.NewJSONEncoder(encCfg), sink, zapcore.DebugLevel)

	var dropped int64
	hook := zapcore.SamplerHook(func(entry zapcore.Entry, dec zapcore.SamplingDecision) {
		if dec&zapcore.LogDropped != 0 {
			atomic.AddInt64(&dropped, 1)
		}
	})

	// thereafter = 0 drops all entries after first N
	samplerCore := zapcore.NewSamplerWithOptions(baseCore, time.Second, 2, 0, hook)
	logger := zap.New(samplerCore)

	for i := 0; i < 10; i++ {
		logger.Info("only first two")
	}

	lines := sink.Lines()
	if len(lines) != 2 {
		t.Fatalf("expected exactly 2 lines when thereafter=0, got %d", len(lines))
	}
	if atomic.LoadInt64(&dropped) != 8 {
		t.Fatalf("expected 8 dropped entries, got %d", dropped)
	}
}

func TestSamplerWithWrapCoreAndChildLogger(t *testing.T) {
	sink := &syncer{}
	encCfg := zapcore.EncoderConfig{
		MessageKey:  "msg",
		LevelKey:    "level",
		EncodeLevel: zapcore.LowercaseLevelEncoder,
	}
	baseCore := zapcore.NewCore(zapcore.NewJSONEncoder(encCfg), sink, zapcore.DebugLevel)
	baseLogger := zap.New(baseCore)

	// Wrap core using zap.WrapCore with SamplerOption
	sampledLogger := baseLogger.WithOptions(zap.WrapCore(func(c zapcore.Core) zapcore.Core {
		return zapcore.NewSamplerWithOptions(c, time.Second, 1, 2)
	}))

	childLogger := sampledLogger.With(zap.String("child", "one"))

	// Base logger should sample
	sampledLogger.Info("test")
	sampledLogger.Info("test") // dropped
	sampledLogger.Info("test") // sampled (seq 3)

	if len(sink.Lines()) != 2 {
		t.Fatalf("expected 2 lines from sampled base logger, got %d", len(sink.Lines()))
	}

	sink.Reset()

	// Child logger shares sampling behavior
	childLogger.Info("child-msg")
	childLogger.Info("child-msg") // dropped
	childLogger.Info("child-msg") // sampled

	if len(sink.Lines()) != 2 {
		t.Fatalf("expected 2 lines from child logger, got %d", len(sink.Lines()))
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Configure rate-limited log sampling using zapcore.NewSamplerWithOptions and verify first N entries and subsequent periodic sampling",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.uber.org/zap@v1.28.0"
  ],
  "symbols": [
    "zapcore.NewSamplerWithOptions",
    "zapcore.SamplerHook",
    "zapcore.SamplerWithOptions"
  ]
}

オリジンシーダー

匿名