CodeSampleX

Exemple

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

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

sha256:256e50166f267b72af7f6dcb466573003437664330037624497f50748f87c098

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-04

Cas

HOW
Objectif
verify go.uber.org/zap/zapcore.EncoderConfig in pkg:golang/go.uber.org/zap@v1.28.0
Paquets
Symboles
  • go.uber.org/zap/zapcore.EncoderConfig
Créé
2026-09-04T17:18:04Z

Contrat

  1. zapcore.EncoderConfig configures custom JSON key names and omits fields when keys are set to empty.
  2. zapcore.EncoderConfig configures custom level, timestamp, duration, and caller formatting via functional encoders.
  3. zapcore.EncoderConfig configures plain-text console output with custom ConsoleSeparator and line endings.

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 zapcore.EncoderConfig Verification

## Prior Findings
Search for known solutions for `go.uber.org/zap/zapcore.EncoderConfig` in `pkg:golang/go.uber.org/zap@v1.28.0` returned `NO_SAFE_MATCH`.
Existing samples covered atomic level switching, in-memory observer logging, custom sink registration, and entry metadata, but did not prove `zapcore.EncoderConfig` serialization behaviors and encoder options.

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

## Observed Behaviour
1. `zapcore.EncoderConfig` customizes JSON field keys (MessageKey, LevelKey, TimeKey, NameKey, CallerKey, StacktraceKey) and completely omits fields when keys are empty strings.
2. `zapcore.EncoderConfig` configures functional primitive encoders (EncodeLevel, EncodeTime, EncodeDuration, EncodeCaller) across both JSON and console formats.
3. `zapcore.EncoderConfig` controls console delimiter spacing with `ConsoleSeparator` and trailing formatting with `LineEnding` / `SkipLineEnding`.
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 go.uber.org/zap/zapcore.EncoderConfig 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:
  - go.uber.org/zap/zapcore.EncoderConfig

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:6fb3c906ecf725770b270e3962d0906f8de3cfa4123883fcfa4d48e63d740278","contract":["zapcore.EncoderConfig configures custom JSON key names and omits fields when keys are set to empty.","zapcore.EncoderConfig configures custom level, timestamp, duration, and caller formatting via functional encoders.","zapcore.EncoderConfig configures plain-text console output with custom ConsoleSeparator and line endings."],"goal":"verify go.uber.org/zap/zapcore.EncoderConfig 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":["go.uber.org/zap/zapcore.EncoderConfig"]},"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.28.0"],"schemaVersion":1,"subject":"pkg:golang/go.uber.org/zap@v1.28.0","symbols":["go.uber.org/zap/zapcore.EncoderConfig"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.22.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 (
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

// BuildCustomJSONEncoderConfig creates an EncoderConfig with custom field keys
// and omits the timestamp field by setting TimeKey to empty.
func BuildCustomJSONEncoderConfig() zapcore.EncoderConfig {
	return zapcore.EncoderConfig{
		MessageKey:     "log_message",
		LevelKey:       "severity",
		TimeKey:        "", // empty key omits timestamp
		NameKey:        "logger_name",
		CallerKey:      "call_site",
		StacktraceKey:  "stack_trace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.CapitalLevelEncoder,
		EncodeDuration: zapcore.StringDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
	}
}

// BuildFormattedJSONEncoderConfig creates an EncoderConfig with functional encoders
// for level, timestamp, duration, and caller formatting.
func BuildFormattedJSONEncoderConfig() zapcore.EncoderConfig {
	return zapcore.EncoderConfig{
		MessageKey:     "msg",
		LevelKey:       "level",
		TimeKey:        "timestamp",
		CallerKey:      "caller",
		EncodeLevel:    zapcore.LowercaseLevelEncoder,
		EncodeTime:     zapcore.RFC3339TimeEncoder,
		EncodeDuration: zapcore.MillisDurationEncoder,
		EncodeCaller:   zapcore.FullCallerEncoder,
		LineEnding:     "\n",
	}
}

// BuildCustomConsoleEncoderConfig creates an EncoderConfig for console output
// configuring custom field separator and line ending.
func BuildCustomConsoleEncoderConfig(separator string, lineEnding string) zapcore.EncoderConfig {
	return zapcore.EncoderConfig{
		MessageKey:       "msg",
		LevelKey:         "level",
		TimeKey:          "ts",
		CallerKey:        "caller",
		ConsoleSeparator: separator,
		LineEnding:       lineEnding,
		EncodeLevel:      zapcore.CapitalLevelEncoder,
		EncodeTime:       zapcore.EpochTimeEncoder,
		EncodeCaller:     zapcore.ShortCallerEncoder,
	}
}

// EncodeJSONEntry encodes an entry and fields using the given EncoderConfig.
func EncodeJSONEntry(cfg zapcore.EncoderConfig, ent zapcore.Entry, fields ...zap.Field) (string, error) {
	enc := zapcore.NewJSONEncoder(cfg)
	buf, err := enc.EncodeEntry(ent, fields)
	if err != nil {
		return "", err
	}
	defer buf.Free()
	return buf.String(), nil
}

// EncodeConsoleEntry encodes an entry and fields into console formatted text.
func EncodeConsoleEntry(cfg zapcore.EncoderConfig, ent zapcore.Entry, fields ...zap.Field) (string, error) {
	enc := zapcore.NewConsoleEncoder(cfg)
	buf, err := enc.EncodeEntry(ent, fields)
	if err != nil {
		return "", err
	}
	defer buf.Free()
	return buf.String(), nil
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify go.uber.org/zap/zapcore.EncoderConfig in pkg:golang/go.uber.org/zap@v1.28.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.uber.org/zap@v1.28.0"
  ],
  "symbols": [
    "go.uber.org/zap/zapcore.EncoderConfig"
  ]
}
test/contract.go
package main

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

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

func main() {
	// Contract Assertion 1:
	// zapcore.EncoderConfig configures custom JSON key names and omits fields when keys are set to empty.
	{
		cfg := sample.BuildCustomJSONEncoderConfig()
		ent := zapcore.Entry{
			Level:      zapcore.InfoLevel,
			Time:       time.Date(2026, time.September, 4, 12, 0, 0, 0, time.UTC),
			LoggerName: "auth.service",
			Message:    "token refreshed",
			Caller:     zapcore.NewEntryCaller(101, "/app/auth/handler.go", 42, true),
		}

		out, err := sample.EncodeJSONEntry(cfg, ent,
			zap.String("user_id", "usr-1234"),
			zap.Duration("elapsed", 1500*time.Millisecond),
		)
		if err != nil {
			fmt.Fprintf(os.Stderr, "EncodeJSONEntry failed: %v\n", err)
			os.Exit(1)
		}

		var parsed map[string]interface{}
		if err := json.Unmarshal([]byte(out), &parsed); err != nil {
			fmt.Fprintf(os.Stderr, "failed to parse json output: %v, raw: %s\n", err, out)
			os.Exit(1)
		}

		if parsed["severity"] != "INFO" {
			fmt.Fprintf(os.Stderr, "expected severity 'INFO', got %v\n", parsed["severity"])
			os.Exit(1)
		}
		if parsed["log_message"] != "token refreshed" {
			fmt.Fprintf(os.Stderr, "expected log_message 'token refreshed', got %v\n", parsed["log_message"])
			os.Exit(1)
		}
		if parsed["logger_name"] != "auth.service" {
			fmt.Fprintf(os.Stderr, "expected logger_name 'auth.service', got %v\n", parsed["logger_name"])
			os.Exit(1)
		}
		if parsed["call_site"] != "auth/handler.go:42" {
			fmt.Fprintf(os.Stderr, "expected call_site 'auth/handler.go:42', got %v\n", parsed["call_site"])
			os.Exit(1)
		}
		if parsed["user_id"] != "usr-1234" {
			fmt.Fprintf(os.Stderr, "expected user_id 'usr-1234', got %v\n", parsed["user_id"])
			os.Exit(1)
		}
		if parsed["elapsed"] != "1.5s" {
			fmt.Fprintf(os.Stderr, "expected elapsed '1.5s', got %v\n", parsed["elapsed"])
			os.Exit(1)
		}

		// Verify that timeKey="" caused the timestamp to be omitted completely
		if _, hasTime := parsed["timestamp"]; hasTime {
			fmt.Fprintf(os.Stderr, "unexpected 'timestamp' key found in JSON\n")
			os.Exit(1)
		}
		if _, hasTs := parsed["ts"]; hasTs {
			fmt.Fprintf(os.Stderr, "unexpected 'ts' key found in JSON\n")
			os.Exit(1)
		}
		if _, hasTimeKey := parsed["time"]; hasTimeKey {
			fmt.Fprintf(os.Stderr, "unexpected 'time' key found in JSON\n")
			os.Exit(1)
		}
	}

	// Contract Assertion 2:
	// zapcore.EncoderConfig configures custom level, timestamp, duration, and caller formatting via functional encoders.
	{
		cfg := sample.BuildFormattedJSONEncoderConfig()
		fixedTime := time.Date(2026, time.September, 4, 15, 30, 0, 0, time.UTC)
		ent := zapcore.Entry{
			Level:   zapcore.WarnLevel,
			Time:    fixedTime,
			Message: "memory threshold approaching",
			Caller:  zapcore.NewEntryCaller(202, "/app/worker/proc.go", 99, true),
		}

		out, err := sample.EncodeJSONEntry(cfg, ent,
			zap.Duration("latency", 250*time.Millisecond),
		)
		if err != nil {
			fmt.Fprintf(os.Stderr, "EncodeJSONEntry failed: %v\n", err)
			os.Exit(1)
		}

		var parsed map[string]interface{}
		if err := json.Unmarshal([]byte(out), &parsed); err != nil {
			fmt.Fprintf(os.Stderr, "failed to parse json output: %v, raw: %s\n", err, out)
			os.Exit(1)
		}

		if parsed["level"] != "warn" {
			fmt.Fprintf(os.Stderr, "expected level 'warn', got %v\n", parsed["level"])
			os.Exit(1)
		}
		if parsed["timestamp"] != "2026-09-04T15:30:00Z" {
			fmt.Fprintf(os.Stderr, "expected timestamp '2026-09-04T15:30:00Z', got %v\n", parsed["timestamp"])
			os.Exit(1)
		}
		if parsed["caller"] != "/app/worker/proc.go:99" {
			fmt.Fprintf(os.Stderr, "expected full caller '/app/worker/proc.go:99', got %v\n", parsed["caller"])
			os.Exit(1)
		}
		// MillisDurationEncoder serializes 250ms as numeric 250
		lat, ok := parsed["latency"].(float64)
		if !ok || int64(lat) != 250 {
			fmt.Fprintf(os.Stderr, "expected latency 250 (numeric), got %v\n", parsed["latency"])
			os.Exit(1)
		}
	}

	// Contract Assertion 3:
	// zapcore.EncoderConfig configures plain-text console output with custom ConsoleSeparator and line endings.
	{
		separator := " | "
		lineEnding := "\n"
		cfg := sample.BuildCustomConsoleEncoderConfig(separator, lineEnding)

		ent := zapcore.Entry{
			Level:   zapcore.ErrorLevel,
			Time:    time.Unix(1700000000, 0),
			Message: "database connection failed",
			Caller:  zapcore.NewEntryCaller(303, "/app/db/conn.go", 55, true),
		}

		out, err := sample.EncodeConsoleEntry(cfg, ent,
			zap.String("db", "primary"),
		)
		if err != nil {
			fmt.Fprintf(os.Stderr, "EncodeConsoleEntry failed: %v\n", err)
			os.Exit(1)
		}

		if !strings.HasSuffix(out, lineEnding) {
			fmt.Fprintf(os.Stderr, "expected console output to end with newline, got %q\n", out)
			os.Exit(1)
		}

		// Verify ConsoleSeparator delimiters
		if !strings.Contains(out, " | ERROR | ") {
			fmt.Fprintf(os.Stderr, "expected ' | ERROR | ' in console output, got %q\n", out)
			os.Exit(1)
		}
		if !strings.Contains(out, " | db/conn.go:55 | ") {
			fmt.Fprintf(os.Stderr, "expected ' | db/conn.go:55 | ' in console output, got %q\n", out)
			os.Exit(1)
		}
		if !strings.Contains(out, "database connection failed") {
			fmt.Fprintf(os.Stderr, "expected message in console output, got %q\n", out)
			os.Exit(1)
		}
		if !strings.Contains(out, `{"db": "primary"}`) {
			fmt.Fprintf(os.Stderr, "expected JSON context in console output, got %q\n", out)
			os.Exit(1)
		}
	}

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

Seeder d'origine

anonyme