CodeSampleX

샘플

go.uber.org/zap v1.28.0: zapcore.Sampler

검증된 샘플 — golang go.uber.org/zap v1.28.0: zapcore.Sampler. go 1.26 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: zapcore.NewSamplerWithOptions allows…

sha256:0d35d980f59ab4cf8adfa6fa0a43485bbb4983de61b979e2474d35bf6d2bcdf1

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1

검증 실행 환경

환경 컨트랙트 단계 실행일
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-01

케이스

HOW
목표
verify zapcore.Sampler in pkg:golang/go.uber.org/zap@v1.28.0
패키지
심벌
  • zapcore.Sampler
환경
go 1.26
생성일
2026-09-01T16:36:34Z

컨트랙트

  1. zapcore.NewSamplerWithOptions allows the first N entries with the same level and message within a tick interval
  2. zapcore.NewSamplerWithOptions drops all entries beyond the first N when thereafter is zero
  3. zapcore.NewSamplerWithOptions allows every Mth entry after the first N entries when thereafter is greater than zero
  4. zapcore.NewSamplerWithOptions maintains independent counters for distinct message strings and log levels
  5. zapcore.SamplerHook receives LogSampled and LogDropped decisions for processed log entries
  6. zapcore.NewSamplerWithOptions resets counters and permits new entries once the tick duration elapses

파일

  • PROMPT.md
  • contract_test.go
  • csx.json
  • go.mod
  • go.sum
  • sample.go
  • spec.json

소스 아티팩트 내려받기 (tar.gz)

소스

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: verify zapcore.Sampler in pkg:golang/go.uber.org/zap@v1.28.0
Kind: HOW

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

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.
contract_test.go
package sample

import (
	"bytes"
	"strings"
	"testing"
	"time"

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

func newBufferCore(buf *bytes.Buffer, enab zapcore.LevelEnabler) zapcore.Core {
	encoderCfg := zapcore.EncoderConfig{
		MessageKey:  "msg",
		LevelKey:    "lvl",
		EncodeLevel: zapcore.LowercaseLevelEncoder,
	}
	return zapcore.NewCore(
		zapcore.NewJSONEncoder(encoderCfg),
		zapcore.AddSync(buf),
		enab,
	)
}

func countLines(buf *bytes.Buffer) int {
	str := strings.TrimSpace(buf.String())
	if str == "" {
		return 0
	}
	return len(strings.Split(str, "\n"))
}

func TestSamplerFirstEntriesAllowed(t *testing.T) {
	var buf bytes.Buffer
	base := newBufferCore(&buf, zapcore.DebugLevel)
	core := NewSampledCore(base, time.Minute, 3, 0)

	logger := zap.New(core)
	for i := 0; i < 5; i++ {
		logger.Info("repeated message")
	}

	if got := countLines(&buf); got != 3 {
		t.Fatalf("expected 3 logs emitted for first=3 with thereafter=0, got %d", got)
	}
}

func TestSamplerDropsAllAfterFirstWhenThereafterZero(t *testing.T) {
	var buf bytes.Buffer
	var stats SamplingStats
	base := newBufferCore(&buf, zapcore.DebugLevel)
	core := NewSampledCore(base, time.Minute, 2, 0, NewStatsHook(&stats))

	logger := zap.New(core)
	for i := 0; i < 10; i++ {
		logger.Info("spike message")
	}

	if got := countLines(&buf); got != 2 {
		t.Fatalf("expected 2 logs emitted, got %d", got)
	}
	if sampled := stats.Sampled.Load(); sampled != 2 {
		t.Fatalf("expected 2 sampled decisions, got %d", sampled)
	}
	if dropped := stats.Dropped.Load(); dropped != 8 {
		t.Fatalf("expected 8 dropped decisions, got %d", dropped)
	}
}

func TestSamplerThereafterInterval(t *testing.T) {
	var buf bytes.Buffer
	base := newBufferCore(&buf, zapcore.DebugLevel)
	core := NewSampledCore(base, time.Minute, 2, 3)

	logger := zap.New(core)
	for i := 0; i < 10; i++ {
		logger.Info("periodic message")
	}

	// 10 entries total: 1st, 2nd (first=2), then 5th (2+3), 8th (2+6). Total = 4.
	if got := countLines(&buf); got != 4 {
		t.Fatalf("expected 4 logs emitted for 10 entries with first=2, thereafter=3; got %d", got)
	}
}

func TestSamplerIndependentCountersPerMessageAndLevel(t *testing.T) {
	var buf bytes.Buffer
	base := newBufferCore(&buf, zapcore.DebugLevel)
	core := NewSampledCore(base, time.Minute, 2, 0)

	logger := zap.New(core)

	for i := 0; i < 4; i++ {
		logger.Info("message A")
	}
	for i := 0; i < 3; i++ {
		logger.Info("message B")
	}
	for i := 0; i < 3; i++ {
		logger.Warn("message A")
	}

	if got := countLines(&buf); got != 6 {
		t.Fatalf("expected 6 total logs emitted (2 per unique msg/level bucket), got %d", got)
	}
}

func TestSamplerHookDecisionTracking(t *testing.T) {
	var buf bytes.Buffer
	var stats SamplingStats
	base := newBufferCore(&buf, zapcore.DebugLevel)
	logger := CreateSampledLogger(base, time.Minute, 1, 2, &stats)

	// Log 5 times: 1st allowed, 2nd dropped, 3rd allowed (1+2), 4th dropped, 5th allowed (1+4)
	for i := 0; i < 5; i++ {
		logger.Info("hook test")
	}

	if sampled := stats.Sampled.Load(); sampled != 3 {
		t.Fatalf("expected 3 sampled decisions, got %d", sampled)
	}
	if dropped := stats.Dropped.Load(); dropped != 2 {
		t.Fatalf("expected 2 dropped decisions, got %d", dropped)
	}
}

func TestSamplerTickReset(t *testing.T) {
	var buf bytes.Buffer
	base := newBufferCore(&buf, zapcore.DebugLevel)
	tick := 10 * time.Millisecond
	core := NewSampledCore(base, tick, 1, 0)

	baseTime := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
	ent1 := zapcore.Entry{Level: zapcore.InfoLevel, Message: "reset test", Time: baseTime}
	ent2 := zapcore.Entry{Level: zapcore.InfoLevel, Message: "reset test", Time: baseTime.Add(2 * time.Millisecond)}
	ent3 := zapcore.Entry{Level: zapcore.InfoLevel, Message: "reset test", Time: baseTime.Add(20 * time.Millisecond)}

	ce1 := core.Check(ent1, nil)
	if ce1 == nil {
		t.Fatal("expected first entry in tick to be checked/sampled")
	}
	ce1.Write()

	ce2 := core.Check(ent2, nil)
	if ce2 != nil {
		t.Fatal("expected second entry within same tick to be dropped")
	}

	ce3 := core.Check(ent3, nil)
	if ce3 == nil {
		t.Fatal("expected entry after tick expiration to be checked/sampled")
	}
	ce3.Write()

	if got := countLines(&buf); got != 2 {
		t.Fatalf("expected 2 logs emitted across tick boundaries, got %d", got)
	}
}
csx.json
{"case":{"caseId":"case:sha256:d2fdfa9dd0e5b71eaf42c7c031ad37ae248d1782fe2f417c879eba10b9127d4a","contract":["zapcore.NewSamplerWithOptions allows the first N entries with the same level and message within a tick interval","zapcore.NewSamplerWithOptions drops all entries beyond the first N when thereafter is zero","zapcore.NewSamplerWithOptions allows every Mth entry after the first N entries when thereafter is greater than zero","zapcore.NewSamplerWithOptions maintains independent counters for distinct message strings and log levels","zapcore.SamplerHook receives LogSampled and LogDropped decisions for processed log entries","zapcore.NewSamplerWithOptions resets counters and permits new entries once the tick duration elapses"],"goal":"verify zapcore.Sampler in pkg:golang/go.uber.org/zap@v1.28.0","kind":"HOW","packages":["pkg:golang/go.uber.org/zap@v1.28.0"],"schemaVersion":1,"symbols":["zapcore.Sampler"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","packageManagerVersion":"1.26.6","runtime":"go","runtimeVersion":"1.26","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.Sampler"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.24.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=
sample.go
package sample

import (
	"sync/atomic"
	"time"

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

// SamplingStats tracks the number of sampled and dropped log decisions.
type SamplingStats struct {
	Sampled atomic.Int64
	Dropped atomic.Int64
}

// NewSampledCore creates a sampled zapcore.Core with the specified tick, first, and thereafter thresholds.
func NewSampledCore(core zapcore.Core, tick time.Duration, first, thereafter int, opts ...zapcore.SamplerOption) zapcore.Core {
	return zapcore.NewSamplerWithOptions(core, tick, first, thereafter, opts...)
}

// NewStatsHook creates a SamplerOption that tracks sampling decisions into SamplingStats.
func NewStatsHook(stats *SamplingStats) zapcore.SamplerOption {
	return zapcore.SamplerHook(func(ent zapcore.Entry, dec zapcore.SamplingDecision) {
		if dec&zapcore.LogSampled != 0 {
			stats.Sampled.Add(1)
		}
		if dec&zapcore.LogDropped != 0 {
			stats.Dropped.Add(1)
		}
	})
}

// CreateSampledLogger constructs a zap.Logger using a sampled core wrapping the provided base core.
func CreateSampledLogger(base zapcore.Core, tick time.Duration, first, thereafter int, stats *SamplingStats) *zap.Logger {
	var opts []zapcore.SamplerOption
	if stats != nil {
		opts = append(opts, NewStatsHook(stats))
	}
	sampledCore := NewSampledCore(base, tick, first, thereafter, opts...)
	return zap.New(sampledCore)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify zapcore.Sampler in pkg:golang/go.uber.org/zap@v1.28.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.uber.org/zap@v1.28.0"
  ],
  "symbols": [
    "zapcore.Sampler"
  ]
}

오리진 시더

익명