CodeSampleX

Sample

go.uber.org/zap v1.26.0: Hooks

Verified sample for golang go.uber.org/zap v1.26.0: Hooks. The contract ran on go 1.26 · linux debian/x64 · docker and passed.

sha256:1a7ec957325aa0709ba94af6779dcd105e3e9232aa79cc971716212e77be6a5e

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
1
Signing keys that built it
1
Declared environment linux 24 · ubuntu · glibc 2.39 x64 go

Verification-run environments

Environment Contract Stages Run
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-03

Case

HOW
Goal
verify zap.Hooks in pkg:golang/go.uber.org/zap@v1.26.0
Packages
Symbols
  • zap.Hooks
Created
2026-09-03T06:28:58Z

Contract

  1. zap.Hooks registers callbacks executed on each written log entry and filters messages below configured level
  2. zap.Hooks executes multiple hooks in registration order and continues calling remaining hooks even if an earlier hook returns an error
  3. zap.Hooks options are additive across repeated WithOptions calls and provide accurate Entry metadata

Files

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • logger.go
  • spec.json
  • test/contract.go

Download the source artifact (tar.gz)

Source

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 zap.Hooks in pkg:golang/go.uber.org/zap@v1.26.0
Kind: HOW

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

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:d941143a282a67e12023949dc73f26d28fc5c2c88f92bc11e6804c99b81c5ea5","contract":["zap.Hooks registers callbacks executed on each written log entry and filters messages below configured level","zap.Hooks executes multiple hooks in registration order and continues calling remaining hooks even if an earlier hook returns an error","zap.Hooks options are additive across repeated WithOptions calls and provide accurate Entry metadata"],"goal":"verify zap.Hooks in pkg:golang/go.uber.org/zap@v1.26.0","kind":"HOW","packages":["pkg:golang/go.uber.org/zap@v1.26.0"],"schemaVersion":1,"symbols":["zap.Hooks"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/go.uber.org/zap@v1.26.0"],"schemaVersion":1,"subject":"pkg:golang/go.uber.org/zap@v1.26.0","symbols":["zap.Hooks"],"verifierAdapter":"golang@1"}
go.mod
module example.com/zaphooks

go 1.22.0

require go.uber.org/zap v1.26.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.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk=
go.uber.org/goleak v1.2.0/go.mod h1:XJYK+MuIchqpmGmUSAzotztawfKvYLUIgg7guXrwVUo=
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.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo=
go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
logger.go
package zaphooks

import (
	"sync"

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

// HookMetrics tracks counts of log entries by level via zap.Hooks callbacks.
type HookMetrics struct {
	mu     sync.Mutex
	counts map[zapcore.Level]int
}

// NewHookMetrics creates a new thread-safe HookMetrics tracker.
func NewHookMetrics() *HookMetrics {
	return &HookMetrics{
		counts: make(map[zapcore.Level]int),
	}
}

// Hook returns a callback function compatible with zap.Hooks that counts logs.
func (m *HookMetrics) Hook() func(zapcore.Entry) error {
	return func(ent zapcore.Entry) error {
		m.mu.Lock()
		defer m.mu.Unlock()
		m.counts[ent.Level]++
		return nil
	}
}

// Count returns the number of logs recorded for the specified level.
func (m *HookMetrics) Count(lvl zapcore.Level) int {
	m.mu.Lock()
	defer m.mu.Unlock()
	return m.counts[lvl]
}

// Total returns the total number of logs recorded across all levels.
func (m *HookMetrics) Total() int {
	m.mu.Lock()
	defer m.mu.Unlock()
	sum := 0
	for _, count := range m.counts {
		sum += count
	}
	return sum
}

// AttachHooks wraps zap.Hooks to return a zap.Option.
func AttachHooks(hooks ...func(zapcore.Entry) error) zap.Option {
	return zap.Hooks(hooks...)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify zap.Hooks in pkg:golang/go.uber.org/zap@v1.26.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.uber.org/zap@v1.26.0"
  ],
  "symbols": [
    "zap.Hooks"
  ]
}
test/contract.go
package main

import (
	"errors"
	"fmt"
	"io"
	"os"
	"sync"
	"time"

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

	zaphooks "example.com/zaphooks"
)

func main() {
	encCfg := zap.NewProductionEncoderConfig()
	core := zapcore.NewCore(
		zapcore.NewJSONEncoder(encCfg),
		zapcore.AddSync(io.Discard),
		zapcore.InfoLevel,
	)

	// Assertion 1: zap.Hooks registers callbacks that execute on each written log entry
	metrics := zaphooks.NewHookMetrics()
	logger1 := zap.New(core, zaphooks.AttachHooks(metrics.Hook()))
	logger1.Info("service starting")
	logger1.Info("processing batch")
	logger1.Warn("high latency detected")

	if metrics.Total() != 3 {
		fmt.Fprintf(os.Stderr, "FAIL: expected 3 total hook calls, got %d\n", metrics.Total())
		os.Exit(1)
	}
	if metrics.Count(zapcore.InfoLevel) != 2 {
		fmt.Fprintf(os.Stderr, "FAIL: expected 2 info logs, got %d\n", metrics.Count(zapcore.InfoLevel))
		os.Exit(1)
	}
	if metrics.Count(zapcore.WarnLevel) != 1 {
		fmt.Fprintf(os.Stderr, "FAIL: expected 1 warn log, got %d\n", metrics.Count(zapcore.WarnLevel))
		os.Exit(1)
	}

	// Assertion 2: Entries filtered below enabled core level do not trigger hooks
	filteredMetrics := zaphooks.NewHookMetrics()
	logger2 := zap.New(core, zap.Hooks(filteredMetrics.Hook()))
	logger2.Debug("debug message below info threshold")
	if filteredMetrics.Total() != 0 {
		fmt.Fprintf(os.Stderr, "FAIL: expected 0 hook calls for filtered debug log, got %d\n", filteredMetrics.Total())
		os.Exit(1)
	}

	// Assertion 3: Multiple hooks in zap.Hooks execute sequentially in registration order
	var mu sync.Mutex
	var callSequence []string
	hookA := func(ent zapcore.Entry) error {
		mu.Lock()
		defer mu.Unlock()
		callSequence = append(callSequence, "hookA:"+ent.Message)
		return nil
	}
	hookB := func(ent zapcore.Entry) error {
		mu.Lock()
		defer mu.Unlock()
		callSequence = append(callSequence, "hookB:"+ent.Message)
		return nil
	}
	logger3 := zap.New(core, zap.Hooks(hookA, hookB))
	logger3.Info("ordered-test")
	if len(callSequence) != 2 || callSequence[0] != "hookA:ordered-test" || callSequence[1] != "hookB:ordered-test" {
		fmt.Fprintf(os.Stderr, "FAIL: unexpected call sequence: %v\n", callSequence)
		os.Exit(1)
	}

	// Assertion 4: All hooks in zap.Hooks execute even when an earlier hook returns an error
	var hookAfterErrorRan bool
	errHook := func(ent zapcore.Entry) error {
		return errors.New("hook non-fatal error")
	}
	subsequentHook := func(ent zapcore.Entry) error {
		hookAfterErrorRan = true
		return nil
	}
	// Direct internal error logs to io.Discard during this test
	logger4 := zap.New(core, zap.Hooks(errHook, subsequentHook), zap.ErrorOutput(zapcore.AddSync(io.Discard)))
	logger4.Info("error-resilience-test")
	if !hookAfterErrorRan {
		fmt.Fprintf(os.Stderr, "FAIL: subsequent hook must execute even if earlier hook returned error\n")
		os.Exit(1)
	}

	// Assertion 5: Repeated use of zap.Hooks (via WithOptions) is additive
	var additiveRecords []string
	h1 := func(ent zapcore.Entry) error {
		additiveRecords = append(additiveRecords, "first:"+ent.Message)
		return nil
	}
	h2 := func(ent zapcore.Entry) error {
		additiveRecords = append(additiveRecords, "second:"+ent.Message)
		return nil
	}
	baseLog := zap.New(core, zap.Hooks(h1))
	extendedLog := baseLog.WithOptions(zap.Hooks(h2))
	extendedLog.Info("additive-entry")
	if len(additiveRecords) != 2 || additiveRecords[0] != "first:additive-entry" || additiveRecords[1] != "second:additive-entry" {
		fmt.Fprintf(os.Stderr, "FAIL: repeated hooks failed to accumulate: %v\n", additiveRecords)
		os.Exit(1)
	}

	// Assertion 6: Callback receives accurate zapcore.Entry metadata
	var captured zapcore.Entry
	entryHook := func(ent zapcore.Entry) error {
		captured = ent
		return nil
	}
	namedLogger := zap.New(core, zap.Hooks(entryHook)).Named("auth_service")
	beforeLog := time.Now()
	namedLogger.Info("payload parsed")
	afterLog := time.Now()

	if captured.LoggerName != "auth_service" {
		fmt.Fprintf(os.Stderr, "FAIL: expected LoggerName 'auth_service', got %q\n", captured.LoggerName)
		os.Exit(1)
	}
	if captured.Message != "payload parsed" {
		fmt.Fprintf(os.Stderr, "FAIL: expected Message 'payload parsed', got %q\n", captured.Message)
		os.Exit(1)
	}
	if captured.Level != zapcore.InfoLevel {
		fmt.Fprintf(os.Stderr, "FAIL: expected InfoLevel, got %v\n", captured.Level)
		os.Exit(1)
	}
	if captured.Time.Before(beforeLog.Add(-time.Second)) || captured.Time.After(afterLog.Add(time.Second)) {
		fmt.Fprintf(os.Stderr, "FAIL: captured timestamp %v out of expected window\n", captured.Time)
		os.Exit(1)
	}

	fmt.Println("PASS: zap.Hooks contract passed")
}

Origin Seeder

anonymous