CodeSampleX

샘플

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

검증된 샘플 — golang go.uber.org/zap v1.26.0: NewStdLog, NewStdLogAt, RedirectStdLog. go 1.26 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:c428da21cd575260262e91f72fc40c2fdc2b3cbcdca6bc92fee00e6552e13fbb

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

실행 증거

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

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

검증 실행 환경

환경 컨트랙트 단계 실행일
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

케이스

HOW
목표
verify pkg:golang/go.uber.org/zap@v1.26.0
패키지
심벌
  • zap.NewStdLog
  • zap.NewStdLogAt
  • zap.RedirectStdLog
  • zap.RedirectStdLogAt
환경
go
생성일
2026-09-03T06:14:58Z

컨트랙트

  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

파일

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

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

소스

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)
	}
}

오리진 시더

익명