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 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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"
  ]
}

原始种子者

匿名