CodeSampleX

Beispiel

go.uber.org/zap v1.26.0: NewStdLog, NewStdLogAt, RedirectStdLog

Verifiziertes Beispiel für golang go.uber.org/zap v1.26.0: NewStdLog, NewStdLogAt, RedirectStdLog. Der Vertrag lief auf go 1.26 · linux debian/x64 · docker…

sha256:c428da21cd575260262e91f72fc40c2fdc2b3cbcdca6bc92fee00e6552e13fbb

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
3
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung go linux 24 · ubuntu · glibc 2.39 x64 go go go

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 FAIL compile:SKIPPED · contract:FAIL · load:SKIPPED · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-03
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 FAIL compile:SKIPPED · contract:FAIL · load:SKIPPED · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-03
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

Fall

HOW
Ziel
verify pkg:golang/go.uber.org/zap@v1.26.0
Pakete
Symbole
  • zap.NewStdLog
  • zap.NewStdLogAt
  • zap.RedirectStdLog
  • zap.RedirectStdLogAt
Umgebung
go
Erstellt
2026-09-03T06:14:58Z

Contract

  1. zap.RedirectStdLog intercepts standard library log output and routes entries to zap at InfoLevel, and invoking the returned restore function reinstates original log routing
  2. zap.RedirectStdLogAt redirects standard library log output to a specified zapcore.Level and returns an error when given an unrecognized level threshold
  3. zap.NewStdLog returns a standard library *log.Logger that dispatches written lines as zap InfoLevel structured log entries
  4. zap.NewStdLogAt returns a standard library *log.Logger routing to a designated zapcore.Level and returns an error for an unrecognized level threshold

Dateien

  • NOTES.md
  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • zap_stdlog_test.go

Quellartefakt herunterladen (tar.gz)

Quelltext

NOTES.md
# zap Standard Library Log Redirection and Logger Construction

## Prior Findings
A search for existing solutions on `go.uber.org/zap` returned compatible samples:
- `sha256:04fc0c107cbd38bfee7ae0fc1da9d91546055682997e3eee211708b9a7b77aea` (In-memory log capture and development vs production `DPanic` behavior)
- `sha256:46df4736d445e122bed613d66d9074610072b234cffa56ec4013cd41d2affee5` (`zap.RegisterSink` custom URL scheme registration and error handling)
- `sha256:b4d93830bc0e5b11f48fcdf14a96fdb8c2a50cbdf593162924b6eef58f61301d` (Dynamic runtime log level adjustment via `zap.AtomicLevel`)
- `sha256:9d74ff5f2155363b85d2bbd68751fe392bd212ab14ccb97cc3cca610b2307199` (Multi-core tee logging with `zapcore.NewTee`)

This sample tests standard library log integration via `zap.RedirectStdLog`, `zap.RedirectStdLogAt`, `zap.NewStdLog`, and `zap.NewStdLogAt`.

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

## Observed Behaviour
1. `zap.RedirectStdLog(logger)` intercepts standard library log output and routes entries to zap at InfoLevel; invoking the returned restore function reinstates original standard log output.
2. `zap.RedirectStdLogAt(logger, level)` redirects standard library log output to a specified `zapcore.Level` and returns an error when given an unrecognized level threshold.
3. `zap.NewStdLog(logger)` returns a standard library `*log.Logger` that dispatches written lines as zap InfoLevel structured log entries.
4. `zap.NewStdLogAt(logger, level)` returns a standard library `*log.Logger` routing to a designated `zapcore.Level` and returns an error for an unrecognized level threshold.
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
Demonstrate these symbols/APIs:
  - zap.NewStdLog
  - zap.NewStdLogAt
  - zap.RedirectStdLog
  - zap.RedirectStdLogAt

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:05a93b77ab85183939f50354474ffb1db991508230a7de417973db5c9cd6c5de","contract":["zap.RedirectStdLog intercepts standard library log output and routes entries to zap at InfoLevel, and invoking the returned restore function reinstates original log routing","zap.RedirectStdLogAt redirects standard library log output to a specified zapcore.Level and returns an error when given an unrecognized level threshold","zap.NewStdLog returns a standard library *log.Logger that dispatches written lines as zap InfoLevel structured log entries","zap.NewStdLogAt returns a standard library *log.Logger routing to a designated zapcore.Level and returns an error for an unrecognized level threshold"],"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.NewStdLog","zap.NewStdLogAt","zap.RedirectStdLog","zap.RedirectStdLogAt"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","executionContext":"go","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","runtime":"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.NewStdLog","zap.NewStdLogAt","zap.RedirectStdLog","zap.RedirectStdLogAt"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.22

require go.uber.org/zap v1.26.0

require go.uber.org/multierr v1.10.0 // indirect
go.sum
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=
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"
  ],
  "symbols": [
    "zap.NewStdLog",
    "zap.NewStdLogAt",
    "zap.RedirectStdLog",
    "zap.RedirectStdLogAt"
  ]
}
zap_stdlog_test.go
package sample

import (
	"bytes"
	"encoding/json"
	"log"
	"strings"
	"testing"

	"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 newTestLogger(level zapcore.LevelEnabler) (*zap.Logger, *syncer) {
	sink := &syncer{}
	encCfg := zapcore.EncoderConfig{
		MessageKey:     "msg",
		LevelKey:       "level",
		EncodeLevel:    zapcore.LowercaseLevelEncoder,
		EncodeDuration: zapcore.StringDurationEncoder,
	}
	core := zapcore.NewCore(
		zapcore.NewJSONEncoder(encCfg),
		sink,
		level,
	)
	return zap.New(core), sink
}

func parseEntry(t *testing.T, line string) map[string]interface{} {
	var entry map[string]interface{}
	if err := json.Unmarshal([]byte(line), &entry); err != nil {
		t.Fatalf("failed to parse log json: %v, raw: %s", err, line)
	}
	return entry
}

func TestRedirectStdLog(t *testing.T) {
	logger, sink := newTestLogger(zapcore.DebugLevel)

	restore := zap.RedirectStdLog(logger)
	defer restore()

	log.Print("std log info message")

	lines := sink.Lines()
	if len(lines) != 1 {
		t.Fatalf("expected 1 log line in sink, got %d", len(lines))
	}

	entry := parseEntry(t, lines[0])
	if entry["level"] != "info" {
		t.Errorf("expected level info, got %v", entry["level"])
	}
	msg, _ := entry["msg"].(string)
	if !strings.Contains(msg, "std log info message") {
		t.Errorf("expected message to contain 'std log info message', got %v", msg)
	}

	restore()
	sink.Reset()

	var fallbackBuf bytes.Buffer
	log.SetOutput(&fallbackBuf)
	log.Print("after restore")

	if sink.buf.Len() != 0 {
		t.Errorf("expected zap sink to receive no logs after restore, got %s", sink.String())
	}
	if !strings.Contains(fallbackBuf.String(), "after restore") {
		t.Errorf("expected fallbackBuf to receive log after restore, got %s", fallbackBuf.String())
	}
}

func TestRedirectStdLogAt(t *testing.T) {
	logger, sink := newTestLogger(zapcore.DebugLevel)

	restore, err := zap.RedirectStdLogAt(logger, zapcore.WarnLevel)
	if err != nil {
		t.Fatalf("unexpected error redirecting at warn level: %v", err)
	}
	defer restore()

	log.Print("std log warn message")

	lines := sink.Lines()
	if len(lines) != 1 {
		t.Fatalf("expected 1 log line in sink, got %d", len(lines))
	}

	entry := parseEntry(t, lines[0])
	if entry["level"] != "warn" {
		t.Errorf("expected level warn, got %v", entry["level"])
	}
	msg, _ := entry["msg"].(string)
	if !strings.Contains(msg, "std log warn message") {
		t.Errorf("expected message to contain 'std log warn message', got %v", msg)
	}

	_, errInvalid := zap.RedirectStdLogAt(logger, zapcore.Level(99))
	if errInvalid == nil {
		t.Errorf("expected error for unrecognized level 99, got nil")
	}
}

func TestNewStdLog(t *testing.T) {
	logger, sink := newTestLogger(zapcore.DebugLevel)

	stdLogger := zap.NewStdLog(logger)
	if stdLogger == nil {
		t.Fatalf("expected non-nil *log.Logger from zap.NewStdLog")
	}

	stdLogger.Println("custom std logger message")

	lines := sink.Lines()
	if len(lines) != 1 {
		t.Fatalf("expected 1 log line in sink, got %d", len(lines))
	}

	entry := parseEntry(t, lines[0])
	if entry["level"] != "info" {
		t.Errorf("expected level info, got %v", entry["level"])
	}
	msg, _ := entry["msg"].(string)
	if !strings.Contains(msg, "custom std logger message") {
		t.Errorf("expected message to contain 'custom std logger message', got %v", msg)
	}
}

func TestNewStdLogAt(t *testing.T) {
	logger, sink := newTestLogger(zapcore.DebugLevel)

	errLogger, err := zap.NewStdLogAt(logger, zapcore.ErrorLevel)
	if err != nil {
		t.Fatalf("unexpected error from zap.NewStdLogAt: %v", err)
	}
	if errLogger == nil {
		t.Fatalf("expected non-nil *log.Logger from zap.NewStdLogAt")
	}

	errLogger.Println("error entry from std logger")

	lines := sink.Lines()
	if len(lines) != 1 {
		t.Fatalf("expected 1 log line in sink, got %d", len(lines))
	}

	entry := parseEntry(t, lines[0])
	if entry["level"] != "error" {
		t.Errorf("expected level error, got %v", entry["level"])
	}
	msg, _ := entry["msg"].(string)
	if !strings.Contains(msg, "error entry from std logger") {
		t.Errorf("expected message to contain 'error entry from std logger', got %v", msg)
	}

	nilLogger, errInvalid := zap.NewStdLogAt(logger, zapcore.Level(99))
	if errInvalid == nil {
		t.Errorf("expected error for unrecognized level 99, got nil")
	}
	if nilLogger != nil {
		t.Errorf("expected nil logger on invalid level, got %v", nilLogger)
	}
}

Ursprungs-Seeder

anonym