CodeSampleX

Exemple

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

Échantillon vérifié pour golang go.uber.org/zap v1.26.0: WrapCore. Le contrat s'est exécuté sur go 1.26 · linux debian/x64 · docker et a réussi.

sha256:0699aadd6b313c27ee541fa0fb99e22b1ef5c2ffd657a5a8d387ababad1d160f

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 go

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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

Cas

HOW
Objectif
verify pkg:golang/go.uber.org/zap@v1.26.0
Paquets
Symboles
  • zap.WrapCore
Créé
2026-09-03T06:07:51Z

Contrat

  1. zap.WrapCore decorates the underlying zapcore.Core to intercept and enrich log entries with structured fields
  2. zap.WrapCore enables custom entry filtering by evaluating entries in Check before forwarding to the base core
  3. logger.WithOptions with zap.WrapCore returns a new logger without mutating the parent logger's core behavior
  4. Multiple zap.WrapCore options compose hierarchically across chained WithOptions calls

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

NOTES.md
# zap Core Customization with zap.WrapCore

## Prior Findings
A search for existing solutions on `go.uber.org/zap@v1.26.0` showed existing coverage for multi-core teeing (`zapcore.NewTee`).
Other zap samples cover `zap.AtomicLevel`, `zap.RegisterSink`, and `zapcore.NewSamplerWithOptions`.
This sample provides coverage for `zap.WrapCore`.

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

## Observed Behaviour
1. `zap.WrapCore` wraps the underlying `zapcore.Core` to intercept and enrich log entries with structured fields.
2. A custom core wrapped via `zap.WrapCore` can selectively filter log entries during `Check`.
3. Invoking `logger.WithOptions(zap.WrapCore(...))` returns a new logger instance without mutating the parent logger.
4. Multiple `zap.WrapCore` options compose hierarchically across chained calls.
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 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

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:8b66f46739e724705f9f82c390b1ef5ad30efa83a200df3cab94edcd9a73def3","contract":["zap.WrapCore decorates the underlying zapcore.Core to intercept and enrich log entries with structured fields","zap.WrapCore enables custom entry filtering by evaluating entries in Check before forwarding to the base core","logger.WithOptions with zap.WrapCore returns a new logger without mutating the parent logger's core behavior","Multiple zap.WrapCore options compose hierarchically across chained WithOptions calls"],"goal":"verify 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.WrapCore"]},"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.WrapCore"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.22

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

import (
	"bytes"
	"strings"

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

// BaseBufferLogger creates a standard zap.Logger that writes JSON entries to the provided buffer at DebugLevel.
func BaseBufferLogger(buf *bytes.Buffer) *zap.Logger {
	encCfg := zapcore.EncoderConfig{
		MessageKey:  "msg",
		LevelKey:    "level",
		EncodeLevel: zapcore.LowercaseLevelEncoder,
	}
	core := zapcore.NewCore(
		zapcore.NewJSONEncoder(encCfg),
		zapcore.AddSync(buf),
		zapcore.DebugLevel,
	)
	return zap.New(core)
}

// InterceptingCore wraps a zapcore.Core and appends an extra field to all written entries.
type InterceptingCore struct {
	zapcore.Core
	ExtraField zapcore.Field
}

// Check implements zapcore.Core.
func (c *InterceptingCore) Check(ent zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {
	if c.Enabled(ent.Level) {
		return ce.AddCore(ent, c)
	}
	return ce
}

// Write implements zapcore.Core, adding the extra field before delegating.
func (c *InterceptingCore) Write(ent zapcore.Entry, fields []zapcore.Field) error {
	fields = append(fields, c.ExtraField)
	return c.Core.Write(ent, fields)
}

// With implements zapcore.Core.
func (c *InterceptingCore) With(fields []zapcore.Field) zapcore.Core {
	return &InterceptingCore{
		Core:       c.Core.With(fields),
		ExtraField: c.ExtraField,
	}
}

// FilteringCore wraps a zapcore.Core and suppresses entries whose message contains the dropKeyword.
type FilteringCore struct {
	zapcore.Core
	DropKeyword string
}

// Check implements zapcore.Core, dropping entries containing DropKeyword.
func (f *FilteringCore) Check(ent zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {
	if !f.Enabled(ent.Level) {
		return ce
	}
	if strings.Contains(ent.Message, f.DropKeyword) {
		return ce
	}
	return ce.AddCore(ent, f)
}

// Write implements zapcore.Core.
func (f *FilteringCore) Write(ent zapcore.Entry, fields []zapcore.Field) error {
	return f.Core.Write(ent, fields)
}

// With implements zapcore.Core.
func (f *FilteringCore) With(fields []zapcore.Field) zapcore.Core {
	return &FilteringCore{
		Core:        f.Core.With(fields),
		DropKeyword: f.DropKeyword,
	}
}

// WrapWithExtraField uses zap.WrapCore to wrap logger's core with InterceptingCore.
func WrapWithExtraField(logger *zap.Logger, field zapcore.Field) *zap.Logger {
	return logger.WithOptions(zap.WrapCore(func(core zapcore.Core) zapcore.Core {
		return &InterceptingCore{
			Core:       core,
			ExtraField: field,
		}
	}))
}

// WrapWithFilter uses zap.WrapCore to wrap logger's core with FilteringCore.
func WrapWithFilter(logger *zap.Logger, dropKeyword string) *zap.Logger {
	return logger.WithOptions(zap.WrapCore(func(core zapcore.Core) zapcore.Core {
		return &FilteringCore{
			Core:        core,
			DropKeyword: dropKeyword,
		}
	}))
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/go.uber.org/zap@v1.26.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.uber.org/zap@v1.26.0"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"os"
	"strings"

	"example.com/sample"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

func parseLines(buf *bytes.Buffer) ([]map[string]interface{}, error) {
	raw := strings.TrimSpace(buf.String())
	if raw == "" {
		return nil, nil
	}
	lines := strings.Split(raw, "\n")
	var result []map[string]interface{}
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}
		var m map[string]interface{}
		if err := json.Unmarshal([]byte(line), &m); err != nil {
			return nil, fmt.Errorf("invalid json %q: %w", line, err)
		}
		result = append(result, m)
	}
	return result, nil
}

func main() {
	var baseBuf bytes.Buffer
	baseLogger := sample.BaseBufferLogger(&baseBuf)

	// 1. zap.WrapCore decorates the underlying zapcore.Core to intercept and enrich log entries with structured fields
	var wrappedBuf bytes.Buffer
	wrappedLogger := sample.BaseBufferLogger(&wrappedBuf)
	enrichedLogger := sample.WrapWithExtraField(wrappedLogger, zap.String("wrapped_by", "interceptor"))

	enrichedLogger.Info("operation succeeded", zap.String("op", "transfer"))
	lines, err := parseLines(&wrappedBuf)
	if err != nil || len(lines) != 1 {
		fmt.Fprintf(os.Stderr, "assertion 1 failed: expected 1 line, got %d (err: %v)\n", len(lines), err)
		os.Exit(1)
	}
	if lines[0]["msg"] != "operation succeeded" || lines[0]["op"] != "transfer" || lines[0]["wrapped_by"] != "interceptor" {
		fmt.Fprintf(os.Stderr, "assertion 1 failed: unexpected fields in entry: %+v\n", lines[0])
		os.Exit(1)
	}

	// 2. zap.WrapCore enables custom entry filtering by evaluating entries in Check before forwarding to the base core
	var filterBuf bytes.Buffer
	filterLogger := sample.BaseBufferLogger(&filterBuf)
	filtered := sample.WrapWithFilter(filterLogger, "HEALTHCHECK")

	filtered.Info("normal request processed")
	filtered.Info("HEALTHCHECK ping received")
	filtered.Warn("service running low on memory")

	filterLines, err := parseLines(&filterBuf)
	if err != nil || len(filterLines) != 2 {
		fmt.Fprintf(os.Stderr, "assertion 2 failed: expected 2 lines, got %d (err: %v)\n", len(filterLines), err)
		os.Exit(1)
	}
	if filterLines[0]["msg"] != "normal request processed" || filterLines[1]["msg"] != "service running low on memory" {
		fmt.Fprintf(os.Stderr, "assertion 2 failed: unexpected entries: %+v\n", filterLines)
		os.Exit(1)
	}

	// 3. logger.WithOptions with zap.WrapCore returns a new logger without mutating the parent logger's core behavior
	baseBuf.Reset()
	baseLogger.Info("message from parent")
	baseLines, err := parseLines(&baseBuf)
	if err != nil || len(baseLines) != 1 {
		fmt.Fprintf(os.Stderr, "assertion 3 failed: expected 1 line in parent, got %d\n", len(baseLines))
		os.Exit(1)
	}
	if _, exists := baseLines[0]["wrapped_by"]; exists {
		fmt.Fprintf(os.Stderr, "assertion 3 failed: parent logger was mutated: %+v\n", baseLines[0])
		os.Exit(1)
	}

	// 4. Multiple zap.WrapCore options compose hierarchically across chained WithOptions calls
	var composeBuf bytes.Buffer
	l := sample.BaseBufferLogger(&composeBuf)
	composed := l.WithOptions(
		zap.WrapCore(func(c zapcore.Core) zapcore.Core {
			return &sample.InterceptingCore{Core: c, ExtraField: zap.String("layer", "1")}
		}),
		zap.WrapCore(func(c zapcore.Core) zapcore.Core {
			return &sample.FilteringCore{Core: c, DropKeyword: "DROP_ME"}
		}),
	)

	composed.Info("accepted message")
	composed.Info("DROP_ME should not appear")

	compLines, err := parseLines(&composeBuf)
	if err != nil || len(compLines) != 1 {
		fmt.Fprintf(os.Stderr, "assertion 4 failed: expected 1 line, got %d\n", len(compLines))
		os.Exit(1)
	}
	if compLines[0]["msg"] != "accepted message" || compLines[0]["layer"] != "1" {
		fmt.Fprintf(os.Stderr, "assertion 4 failed: unexpected entry content: %+v\n", compLines[0])
		os.Exit(1)
	}

	fmt.Println("All contract assertions passed successfully.")
}

Seeder d'origine

anonyme