CodeSampleX

샘플

github.com/go-logr/logr v1.4.1

검증된 샘플 — golang github.com/go-logr/logr v1.4.1. go 1.26 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: funcr.NewJSON creates a Logger that formats…

sha256:1145de1f8bae6485b842008a26194bd9d37a3c8e147b6c2ee8a831492afc7069

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

실행 증거

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

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

검증 실행 환경

환경 컨트랙트 단계 실행일
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-24

케이스

HOW
목표
verify pkg:golang/github.com/go-logr/logr@v1.4.1
패키지
생성일
2026-08-24T20:16:44Z

컨트랙트

  1. funcr.NewJSON creates a Logger that formats structured log entries as valid JSON strings
  2. funcr.Options with LogCaller enables caller file and line annotations in JSON output
  3. testr.NewWithInterface creates a test logger attached to a custom TestingT implementation
  4. logr.FromSlogHandler converts a standard library slog.Handler into a logr.Logger
  5. logr.ToSlogHandler adapts a logr.Logger into a standard library slog.Handler
  6. logr.Logger.WithCallDepth adjusts caller frame attribution in helper logging functions

파일

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

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

소스

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/github.com/go-logr/logr@v1.4.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/go-logr/logr@v1.4.1

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:6a3ae6c1478244818ac7d5bd59c741b64c9887b40e17fab331070fd8d7658cfb","contract":["funcr.NewJSON creates a Logger that formats structured log entries as valid JSON strings","funcr.Options with LogCaller enables caller file and line annotations in JSON output","testr.NewWithInterface creates a test logger attached to a custom TestingT implementation","logr.FromSlogHandler converts a standard library slog.Handler into a logr.Logger","logr.ToSlogHandler adapts a logr.Logger into a standard library slog.Handler","logr.Logger.WithCallDepth adjusts caller frame attribution in helper logging functions"],"goal":"verify pkg:golang/github.com/go-logr/logr@v1.4.1","kind":"HOW","packages":["pkg:golang/github.com/go-logr/logr@v1.4.1"],"schemaVersion":1},"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/github.com/go-logr/logr@v1.4.1"],"schemaVersion":1,"subject":"pkg:golang/github.com/go-logr/logr@v1.4.1","verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.26.6

require github.com/go-logr/logr v1.4.1
go.sum
github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ=
github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
main.go
package main

import (
	"bytes"
	"fmt"
	"log/slog"
	"os"

	"github.com/go-logr/logr"
	"github.com/go-logr/logr/funcr"
)

func logHelper(l logr.Logger, msg string, kvs ...any) {
	// WithCallDepth(1) adjusts caller frame to point to the caller of logHelper
	l.WithCallDepth(1).Info(msg, kvs...)
}

func main() {
	// Initialize structured JSON logging
	jsonLogger := funcr.NewJSON(func(obj string) {
		fmt.Fprintln(os.Stdout, obj)
	}, funcr.Options{
		LogTimestamp: true,
		Verbosity:    1,
	})

	appLogger := jsonLogger.WithName("service").WithValues("env", "production")
	appLogger.Info("service initialized", "version", "1.0.0")

	// Call helper logger with call depth adjustment
	logHelper(appLogger, "background task completed", "jobId", 42)

	// Interoperability with standard library slog
	var slogBuf bytes.Buffer
	slogHandler := slog.NewJSONHandler(&slogBuf, &slog.HandlerOptions{
		Level: slog.LevelDebug,
	})
	slogAdaptedLogger := logr.FromSlogHandler(slogHandler)
	slogAdaptedLogger.Info("slog adapter active", "mode", "interop")

	// Convert logr.Logger back to slog.Handler
	slogLogger := slog.New(logr.ToSlogHandler(appLogger))
	slogLogger.Info("slog using logr backend", "status", "ready")
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/go-logr/logr@v1.4.1",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/go-logr/logr@v1.4.1"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log/slog"
	"os"
	"strings"
	"sync"

	"github.com/go-logr/logr"
	"github.com/go-logr/logr/funcr"
	"github.com/go-logr/logr/testr"
)

type mockTestingT struct {
	mu           sync.Mutex
	logs         []string
	helperCalled int
}

func (m *mockTestingT) Helper() {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.helperCalled++
}

func (m *mockTestingT) Log(args ...any) {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.logs = append(m.logs, fmt.Sprint(args...))
}

func logHelper(l logr.Logger, msg string, kvs ...any) {
	l.WithCallDepth(1).Info(msg, kvs...)
}

func logWithoutDepth(l logr.Logger, msg string, kvs ...any) {
	l.Info(msg, kvs...)
}

func main() {
	// Contract 1: funcr.NewJSON creates a Logger that formats structured log entries as valid JSON strings
	{
		var lines []string
		var mu sync.Mutex
		logger := funcr.NewJSON(func(obj string) {
			mu.Lock()
			defer mu.Unlock()
			lines = append(lines, obj)
		}, funcr.Options{})

		subLogger := logger.WithName("service").WithValues("component", "gateway")
		subLogger.Info("request received", "path", "/api/v1/resource", "code", 200)

		if len(lines) != 1 {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 1]: expected 1 line, got %d\n", len(lines))
			os.Exit(1)
		}

		var payload map[string]any
		if err := json.Unmarshal([]byte(lines[0]), &payload); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 1]: invalid JSON output: %v, raw: %s\n", err, lines[0])
			os.Exit(1)
		}

		if payload["logger"] != "service" {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 1]: expected logger='service', got %v\n", payload["logger"])
			os.Exit(1)
		}
		if payload["msg"] != "request received" {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 1]: expected msg='request received', got %v\n", payload["msg"])
			os.Exit(1)
		}
		if payload["component"] != "gateway" {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 1]: expected component='gateway', got %v\n", payload["component"])
			os.Exit(1)
		}
		if payload["path"] != "/api/v1/resource" {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 1]: expected path='/api/v1/resource', got %v\n", payload["path"])
			os.Exit(1)
		}
		if payload["code"] != float64(200) {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 1]: expected code=200, got %v\n", payload["code"])
			os.Exit(1)
		}
	}

	// Contract 2: funcr.Options with LogCaller enables caller file and line annotations in JSON output
	{
		var lines []string
		var mu sync.Mutex
		logger := funcr.NewJSON(func(obj string) {
			mu.Lock()
			defer mu.Unlock()
			lines = append(lines, obj)
		}, funcr.Options{
			LogCaller: funcr.All,
		})

		logger.Info("testing caller tracking")
		if len(lines) != 1 {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 2]: expected 1 line, got %d\n", len(lines))
			os.Exit(1)
		}

		var payload map[string]any
		if err := json.Unmarshal([]byte(lines[0]), &payload); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 2]: invalid JSON: %v\n", err)
			os.Exit(1)
		}

		callerVal, ok := payload["caller"]
		if !ok {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 2]: 'caller' field missing in JSON: %s\n", lines[0])
			os.Exit(1)
		}
		callerMap, ok := callerVal.(map[string]any)
		if !ok {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 2]: 'caller' is not a JSON object: %T %v\n", callerVal, callerVal)
			os.Exit(1)
		}
		if _, hasFile := callerMap["file"]; !hasFile {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 2]: 'caller.file' missing: %v\n", callerMap)
			os.Exit(1)
		}
		if _, hasLine := callerMap["line"]; !hasLine {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 2]: 'caller.line' missing: %v\n", callerMap)
			os.Exit(1)
		}
	}

	// Contract 3: testr.NewWithInterface creates a test logger attached to a custom TestingT implementation
	{
		mockT := &mockTestingT{}
		tLogger := testr.NewWithInterface(mockT, testr.Options{
			Verbosity: 1,
		})

		tLogger.Info("test execution started", "case", "contract-test")
		tLogger.V(1).Info("verbose step completed", "step", 1)
		tLogger.V(2).Info("debug details suppressed", "detail", "hidden")

		mockT.mu.Lock()
		logCount := len(mockT.logs)
		logsCopy := append([]string(nil), mockT.logs...)
		helpers := mockT.helperCalled
		mockT.mu.Unlock()

		if logCount != 2 {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 3]: expected exactly 2 logs (V0 and V1), got %d: %v\n", logCount, logsCopy)
			os.Exit(1)
		}
		if helpers < 2 {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 3]: expected Helper() to be called at least twice, got %d\n", helpers)
			os.Exit(1)
		}
		if !strings.Contains(logsCopy[0], "test execution started") || !strings.Contains(logsCopy[0], "contract-test") {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 3]: unexpected first log line: %s\n", logsCopy[0])
			os.Exit(1)
		}
		if !strings.Contains(logsCopy[1], "verbose step completed") {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 3]: unexpected second log line: %s\n", logsCopy[1])
			os.Exit(1)
		}
	}

	// Contract 4: logr.FromSlogHandler converts a standard library slog.Handler into a logr.Logger
	{
		var buf bytes.Buffer
		handler := slog.NewJSONHandler(&buf, &slog.HandlerOptions{
			Level: slog.LevelDebug,
		})
		slogLogger := logr.FromSlogHandler(handler)

		slogLogger.WithName("slog-bridge").WithValues("env", "test").Info("dispatched task", "items", 5)
		slogLogger.V(4).Info("debug level task details", "extra", "trace")

		out := buf.String()
		lines := strings.Split(strings.TrimSpace(out), "\n")
		if len(lines) != 2 {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 4]: expected 2 lines from slog handler, got %d: %s\n", len(lines), out)
			os.Exit(1)
		}

		var line1, line2 map[string]any
		if err := json.Unmarshal([]byte(lines[0]), &line1); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 4]: invalid json line 1: %v\n", err)
			os.Exit(1)
		}
		if err := json.Unmarshal([]byte(lines[1]), &line2); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 4]: invalid json line 2: %v\n", err)
			os.Exit(1)
		}

		if line1["msg"] != "dispatched task" || line1["level"] != "INFO" || line1["items"] != float64(5) {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 4]: unexpected line 1 payload: %v\n", line1)
			os.Exit(1)
		}
		if line2["msg"] != "debug level task details" || line2["level"] != "DEBUG" {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 4]: unexpected line 2 payload (expected DEBUG level for V(4)): %v\n", line2)
			os.Exit(1)
		}
	}

	// Contract 5: logr.ToSlogHandler adapts a logr.Logger into a standard library slog.Handler
	{
		var captured []string
		var mu sync.Mutex
		baseLogger := funcr.NewJSON(func(obj string) {
			mu.Lock()
			defer mu.Unlock()
			captured = append(captured, obj)
		}, funcr.Options{
			Verbosity: 4,
		})

		slogHandler := logr.ToSlogHandler(baseLogger)
		slogInst := slog.New(slogHandler)

		slogInst.Info("slog message to logr", "user", "alice")
		slogInst.Error("slog error to logr", "code", 500)

		if len(captured) != 2 {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 5]: expected 2 logs captured from ToSlogHandler, got %d\n", len(captured))
			os.Exit(1)
		}

		var infoEntry, errEntry map[string]any
		if err := json.Unmarshal([]byte(captured[0]), &infoEntry); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 5]: invalid info JSON: %v\n", err)
			os.Exit(1)
		}
		if err := json.Unmarshal([]byte(captured[1]), &errEntry); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 5]: invalid err JSON: %v\n", err)
			os.Exit(1)
		}

		if infoEntry["msg"] != "slog message to logr" || infoEntry["user"] != "alice" {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 5]: unexpected info payload: %v\n", infoEntry)
			os.Exit(1)
		}
		if errEntry["msg"] != "slog error to logr" || errEntry["code"] != float64(500) {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 5]: unexpected error payload: %v\n", errEntry)
			os.Exit(1)
		}
	}

	// Contract 6: logr.Logger.WithCallDepth adjusts caller frame attribution in helper logging functions
	{
		var captured []string
		var mu sync.Mutex
		baseLogger := funcr.NewJSON(func(obj string) {
			mu.Lock()
			defer mu.Unlock()
			captured = append(captured, obj)
		}, funcr.Options{
			LogCaller: funcr.All,
		})

		logHelper(baseLogger, "from helper with depth")
		logWithoutDepth(baseLogger, "from helper without depth")

		if len(captured) != 2 {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 6]: expected 2 lines, got %d\n", len(captured))
			os.Exit(1)
		}

		var withDepth, withoutDepth map[string]any
		_ = json.Unmarshal([]byte(captured[0]), &withDepth)
		_ = json.Unmarshal([]byte(captured[1]), &withoutDepth)

		caller1 := withDepth["caller"].(map[string]any)
		caller2 := withoutDepth["caller"].(map[string]any)

		line1 := int(caller1["line"].(float64))
		line2 := int(caller2["line"].(float64))

		if line1 == line2 {
			fmt.Fprintf(os.Stderr, "FAIL [Contract 6]: expected different caller line numbers with WithCallDepth, got %d and %d\n", line1, line2)
			os.Exit(1)
		}
	}

	fmt.Println("PASS: pkg:golang/github.com/go-logr/logr@v1.4.1 contract verified")
}

오리진 시더

익명