CodeSampleX

示例

github.com/go-logr/logr v1.3.0: Logger

已验证示例 — golang github.com/go-logr/logr v1.3.0: Logger. contract 在 go 1.26 · linux debian/x64 · docker 上运行并通过: Logger.Info formats message and structured…

sha256:b3c953415ca701c46f5c551d7bc5a729d463bec49e16ab2f7b6e533ca3dd96d0

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux 24 · ubuntu · glibc 2.39 x64 go

验证运行环境

环境 契约 阶段 运行日期
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

案例

HOW
目标
verify github.com/go-logr/logr.Logger in pkg:golang/github.com/go-logr/logr@v1.3.0
包
符号
  • github.com/go-logr/logr.Logger
创建时间
2026-09-04T13:57:01Z

契约

  1. Logger.Info formats message and structured key-value attributes to the underlying LogSink
  2. Logger.Error records error instances alongside explanatory message and structured key-values
  3. Logger.WithName creates a child Logger with hierarchical name segments
  4. Logger.WithValues creates an immutable child Logger that appends key-value pairs without mutating the receiver
  5. Logger.V controls verbosity filtering where levels above the sink threshold are disabled
  6. Logger.IsZero distinguishes uninitialized loggers from active sink loggers while logr.Discard produces an operational no-op logger

文件

  • 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 github.com/go-logr/logr.Logger in pkg:golang/github.com/go-logr/logr@v1.3.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/go-logr/logr@v1.3.0
Demonstrate these symbols/APIs:
  - github.com/go-logr/logr.Logger

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:3121a8882308253090b1343d0268ec1d51512214e05be668042bc9f97734f9c8","contract":["Logger.Info formats message and structured key-value attributes to the underlying LogSink","Logger.Error records error instances alongside explanatory message and structured key-values","Logger.WithName creates a child Logger with hierarchical name segments","Logger.WithValues creates an immutable child Logger that appends key-value pairs without mutating the receiver","Logger.V controls verbosity filtering where levels above the sink threshold are disabled","Logger.IsZero distinguishes uninitialized loggers from active sink loggers while logr.Discard produces an operational no-op logger"],"goal":"verify github.com/go-logr/logr.Logger in pkg:golang/github.com/go-logr/logr@v1.3.0","kind":"HOW","packages":["pkg:golang/github.com/go-logr/logr@v1.3.0"],"schemaVersion":1,"symbols":["github.com/go-logr/logr.Logger"]},"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.3.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/go-logr/logr@v1.3.0","symbols":["github.com/go-logr/logr.Logger"],"verifierAdapter":"golang@1"}
go.mod
module example.com/logr-logger

go 1.26.6

require github.com/go-logr/logr v1.3.0
go.sum
github.com/go-logr/logr v1.3.0 h1:2y3SDp0ZXuc6/cjLSZ+Q3ir+QB9T/iG5yYRXqsagWSY=
github.com/go-logr/logr v1.3.0/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
main.go
package main

import (
	"errors"
	"fmt"
	"os"

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

func main() {
	// Create a structured JSON logger using funcr
	var logger logr.Logger = funcr.NewJSON(func(obj string) {
		fmt.Fprintln(os.Stdout, obj)
	}, funcr.Options{
		Verbosity: 1,
	})

	// Basic logging with key-value pairs
	logger.Info("application starting", "version", "1.0.0", "port", 8080)

	// Sub-logger with namespace hierarchy
	serviceLog := logger.WithName("service").WithValues("service_name", "user-api")
	serviceLog.Info("request handled", "endpoint", "users", "status", 200)

	// Verbose logging: V(1) enabled, V(2) filtered out
	serviceLog.V(1).Info("cache check", "hit", true)
	serviceLog.V(2).Info("detailed trace", "payload_bytes", 1024)

	// Error logging
	err := errors.New("connection timeout")
	serviceLog.Error(err, "database query failed", "query_id", "q-42")

	// Discard logger
	discard := logr.Discard()
	discard.Info("this is discarded")
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/go-logr/logr.Logger in pkg:golang/github.com/go-logr/logr@v1.3.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/go-logr/logr@v1.3.0"
  ],
  "symbols": [
    "github.com/go-logr/logr.Logger"
  ]
}
test/contract.go
package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"os"
	"sync"

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

type logCollector struct {
	mu    sync.Mutex
	lines []string
}

func (c *logCollector) append(line string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.lines = append(c.lines, line)
}

func (c *logCollector) popAll() []string {
	c.mu.Lock()
	defer c.mu.Unlock()
	out := c.lines
	c.lines = nil
	return out
}

func main() {
	// Assertion 1: Logger.Info formats message and structured key-value attributes to the underlying LogSink
	{
		col := &logCollector{}
		logger := funcr.NewJSON(col.append, funcr.Options{})

		if !logger.Enabled() {
			fmt.Fprintln(os.Stderr, "FAIL [Assertion 1]: expected logger.Enabled() to be true")
			os.Exit(1)
		}

		logger.Info("user logged in", "user_id", 101, "status", "active")

		lines := col.popAll()
		if len(lines) != 1 {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 1]: expected 1 log 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 [Assertion 1]: invalid JSON output: %v\n", err)
			os.Exit(1)
		}

		if payload["msg"] != "user logged in" {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 1]: expected msg 'user logged in', got %v\n", payload["msg"])
			os.Exit(1)
		}
		if payload["user_id"] != float64(101) {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 1]: expected user_id 101, got %v\n", payload["user_id"])
			os.Exit(1)
		}
		if payload["status"] != "active" {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 1]: expected status 'active', got %v\n", payload["status"])
			os.Exit(1)
		}
	}

	// Assertion 2: Logger.Error records error instances alongside explanatory message and structured key-values
	{
		col := &logCollector{}
		logger := funcr.NewJSON(col.append, funcr.Options{})

		errFailed := errors.New("disk full")
		logger.Error(errFailed, "write failed", "path", "data/file.txt", "retry", 2)

		lines := col.popAll()
		if len(lines) != 1 {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 2]: expected 1 log 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 [Assertion 2]: invalid JSON output: %v\n", err)
			os.Exit(1)
		}

		if payload["msg"] != "write failed" {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 2]: expected msg 'write failed', got %v\n", payload["msg"])
			os.Exit(1)
		}
		if payload["error"] != "disk full" {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 2]: expected error 'disk full', got %v\n", payload["error"])
			os.Exit(1)
		}
		if payload["path"] != "data/file.txt" {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 2]: expected path 'data/file.txt', got %v\n", payload["path"])
			os.Exit(1)
		}
		if payload["retry"] != float64(2) {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 2]: expected retry 2, got %v\n", payload["retry"])
			os.Exit(1)
		}
	}

	// Assertion 3: Logger.WithName creates a child Logger with hierarchical name segments
	{
		col := &logCollector{}
		root := funcr.NewJSON(col.append, funcr.Options{})

		authLog := root.WithName("auth")
		oauthLog := authLog.WithName("oauth")

		oauthLog.Info("token generated")
		lines := col.popAll()
		if len(lines) != 1 {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 3]: expected 1 line for child logger, got %d\n", len(lines))
			os.Exit(1)
		}

		var childPayload map[string]any
		if err := json.Unmarshal([]byte(lines[0]), &childPayload); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 3]: invalid JSON from child logger: %v\n", err)
			os.Exit(1)
		}
		if childPayload["logger"] != "auth/oauth" {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 3]: expected logger 'auth/oauth', got %v\n", childPayload["logger"])
			os.Exit(1)
		}

		// Root logger is not modified
		root.Info("root event")
		lines = col.popAll()
		if len(lines) != 1 {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 3]: expected 1 line for root logger, got %d\n", len(lines))
			os.Exit(1)
		}
		var rootPayload map[string]any
		if err := json.Unmarshal([]byte(lines[0]), &rootPayload); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 3]: invalid JSON from root logger: %v\n", err)
			os.Exit(1)
		}
		if rootPayload["logger"] != "" {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 3]: expected empty logger name for root, got %v\n", rootPayload["logger"])
			os.Exit(1)
		}
	}

	// Assertion 4: Logger.WithValues creates an immutable child Logger that appends key-value pairs without mutating the receiver
	{
		col := &logCollector{}
		base := funcr.NewJSON(col.append, funcr.Options{}).WithValues("env", "prod")

		child := base.WithValues("request_id", "req-99")

		child.Info("child message")
		lines := col.popAll()
		if len(lines) != 1 {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 4]: expected 1 child line, got %d\n", len(lines))
			os.Exit(1)
		}

		var childPayload map[string]any
		if err := json.Unmarshal([]byte(lines[0]), &childPayload); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 4]: invalid child JSON: %v\n", err)
			os.Exit(1)
		}
		if childPayload["env"] != "prod" || childPayload["request_id"] != "req-99" {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 4]: expected env=prod and request_id=req-99, got %v\n", childPayload)
			os.Exit(1)
		}

		// Base logger does not have request_id
		base.Info("base message")
		lines = col.popAll()
		if len(lines) != 1 {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 4]: expected 1 base line, got %d\n", len(lines))
			os.Exit(1)
		}

		var basePayload map[string]any
		if err := json.Unmarshal([]byte(lines[0]), &basePayload); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 4]: invalid base JSON: %v\n", err)
			os.Exit(1)
		}
		if basePayload["env"] != "prod" {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 4]: expected env=prod in base, got %v\n", basePayload["env"])
			os.Exit(1)
		}
		if _, exists := basePayload["request_id"]; exists {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 4]: base logger unexpectedly mutated with request_id\n")
			os.Exit(1)
		}
	}

	// Assertion 5: Logger.V controls verbosity filtering where levels above the sink threshold are disabled
	{
		col := &logCollector{}
		logger := funcr.NewJSON(col.append, funcr.Options{
			Verbosity: 1,
		})

		if !logger.V(0).Enabled() {
			fmt.Fprintln(os.Stderr, "FAIL [Assertion 5]: expected V(0).Enabled() to be true")
			os.Exit(1)
		}
		if !logger.V(1).Enabled() {
			fmt.Fprintln(os.Stderr, "FAIL [Assertion 5]: expected V(1).Enabled() to be true")
			os.Exit(1)
		}
		if logger.V(2).Enabled() {
			fmt.Fprintln(os.Stderr, "FAIL [Assertion 5]: expected V(2).Enabled() to be false")
			os.Exit(1)
		}

		if logger.V(1).GetV() != 1 {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 5]: expected GetV() == 1, got %d\n", logger.V(1).GetV())
			os.Exit(1)
		}
		if logger.V(2).GetV() != 2 {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 5]: expected GetV() == 2, got %d\n", logger.V(2).GetV())
			os.Exit(1)
		}

		// Message with V(2) must not be logged
		logger.V(2).Info("suppressed trace")
		lines := col.popAll()
		if len(lines) != 0 {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 5]: V(2) message was unexpectedly logged: %v\n", lines)
			os.Exit(1)
		}

		// Message with V(1) must be logged
		logger.V(1).Info("active debug")
		lines = col.popAll()
		if len(lines) != 1 {
			fmt.Fprintf(os.Stderr, "FAIL [Assertion 5]: expected 1 line for V(1), got %d\n", len(lines))
			os.Exit(1)
		}
	}

	// Assertion 6: Logger.IsZero distinguishes uninitialized loggers from active sink loggers while logr.Discard produces an operational no-op logger
	{
		var zero logr.Logger
		if !zero.IsZero() {
			fmt.Fprintln(os.Stderr, "FAIL [Assertion 6]: expected zero.IsZero() == true")
			os.Exit(1)
		}
		if zero.Enabled() {
			fmt.Fprintln(os.Stderr, "FAIL [Assertion 6]: expected zero.Enabled() == false")
			os.Exit(1)
		}
		if zero.GetSink() != nil {
			fmt.Fprintln(os.Stderr, "FAIL [Assertion 6]: expected zero.GetSink() == nil")
			os.Exit(1)
		}

		active := funcr.NewJSON(func(string) {}, funcr.Options{})
		if active.IsZero() {
			fmt.Fprintln(os.Stderr, "FAIL [Assertion 6]: expected active logger IsZero() == false")
			os.Exit(1)
		}
		if !active.Enabled() {
			fmt.Fprintln(os.Stderr, "FAIL [Assertion 6]: expected active logger Enabled() == true")
			os.Exit(1)
		}
		if active.GetSink() == nil {
			fmt.Fprintln(os.Stderr, "FAIL [Assertion 6]: expected active logger GetSink() != nil")
			os.Exit(1)
		}

		discard := logr.Discard()
		if !discard.IsZero() {
			fmt.Fprintln(os.Stderr, "FAIL [Assertion 6]: expected discard.IsZero() == true")
			os.Exit(1)
		}
		if discard.Enabled() {
			fmt.Fprintln(os.Stderr, "FAIL [Assertion 6]: expected discard.Enabled() == false")
			os.Exit(1)
		}

		// Operations on discard logger must execute safely without panicking
		discard.Info("no-op info", "k", "v")
		discard.Error(errors.New("test error"), "no-op error", "k", "v")
		subDiscard := discard.WithName("test").WithValues("k", "v")
		subDiscard.Info("nested discard")
	}

	fmt.Println("PASS: github.com/go-logr/logr.Logger contract verified")
}

原始种子者

匿名