CodeSampleX

Ejemplo

github.com/go-kit/log v0.1.0: NewStdlibAdapter

Muestra verificada para golang github.com/go-kit/log v0.1.0: NewStdlibAdapter. El contrato se ejecutó en go 1.26 · linux debian/x64 · docker y pasó.

sha256:5678d6167255eb4fd52de6fb20dd6d84bfad3f8884b90bb0a1a706d8a86d8fc9

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 go

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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

Caso

HOW
Objetivo
verify pkg:golang/github.com/go-kit/log@v0.1.0
Paquetes
Símbolos
  • log.NewStdlibAdapter
Creado
2026-09-03T17:51:22Z

Contrato

  1. log.NewStdlibAdapter redirects standard library log events to a structured logger
  2. log.NewStdlibAdapter extracts timestamp into the default ts field
  3. log.NewStdlibAdapter extracts caller file and line into the default caller field
  4. log.MessageKey, log.TimestampKey, and log.FileKey configure custom field names for extracted data
  5. log.Prefix strips standard library prefixes or retains them when joinPrefixToMsg is true
  6. log.NewStdlibAdapter supports thread-safe concurrent writes from multiple goroutines

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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-kit/log@v0.1.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/go-kit/log@v0.1.0

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:d3d8a4f98714919cc292e282125befe8abac3d8b6565c6093769209417579a1b","contract":["log.NewStdlibAdapter redirects standard library log events to a structured logger","log.NewStdlibAdapter extracts timestamp into the default ts field","log.NewStdlibAdapter extracts caller file and line into the default caller field","log.MessageKey, log.TimestampKey, and log.FileKey configure custom field names for extracted data","log.Prefix strips standard library prefixes or retains them when joinPrefixToMsg is true","log.NewStdlibAdapter supports thread-safe concurrent writes from multiple goroutines"],"goal":"verify pkg:golang/github.com/go-kit/log@v0.1.0","kind":"HOW","packages":["pkg:golang/github.com/go-kit/log@v0.1.0"],"schemaVersion":1,"symbols":["log.NewStdlibAdapter"]},"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-kit/log@v0.1.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/go-kit/log@v0.1.0","symbols":["log.NewStdlibAdapter"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require github.com/go-kit/log v0.1.0

require github.com/go-logfmt/logfmt v0.5.0 // indirect
go.sum
github.com/go-kit/log v0.1.0 h1:DGJh0Sm43HbOeYDNnVZFl8BvcYVvjD5bqYJvp0REbwQ=
github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY=
github.com/go-logfmt/logfmt v0.5.0 h1:TrB8swr/68K7m9CcGut2g3UOihhbcbiMAYiuTXdEih4=
github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A=
github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/go-kit/log@v0.1.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/go-kit/log@v0.1.0"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"fmt"
	stdlog "log"
	"os"
	"regexp"
	"strings"
	"sync"

	"github.com/go-kit/log"
)

func main() {
	if err := runContractTests(); err != nil {
		fmt.Fprintf(os.Stderr, "Contract test failed: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("All contract tests passed successfully.")
}

func runContractTests() error {
	var buf bytes.Buffer
	baseLogger := log.NewLogfmtLogger(&buf)

	// 1. log.NewStdlibAdapter redirects standard library log events to a structured logger
	{
		buf.Reset()
		adapter := log.NewStdlibAdapter(baseLogger)
		l := stdlog.New(adapter, "", 0)
		l.Print("service initialized successfully")

		out := strings.TrimSpace(buf.String())
		expected := `msg="service initialized successfully"`
		if out != expected {
			return fmt.Errorf("assertion 1 failed: expected %q, got %q", expected, out)
		}
	}

	// 2. log.NewStdlibAdapter extracts timestamp into the default ts field
	{
		buf.Reset()
		adapter := log.NewStdlibAdapter(baseLogger)
		l := stdlog.New(adapter, "", stdlog.Ldate|stdlog.Ltime)
		l.Print("timestamped event")

		out := strings.TrimSpace(buf.String())
		tsRegex := regexp.MustCompile(`^ts="[0-9]{4}/[0-9]{2}/[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}" msg="timestamped event"$`)
		if !tsRegex.MatchString(out) {
			return fmt.Errorf("assertion 2 failed: output %q did not match timestamp pattern", out)
		}
	}

	// 3. log.NewStdlibAdapter extracts caller file and line into the default caller field
	{
		buf.Reset()
		adapter := log.NewStdlibAdapter(baseLogger)
		l := stdlog.New(adapter, "", stdlog.Lshortfile)
		l.Print("caller tracked event")

		out := strings.TrimSpace(buf.String())
		callerRegex := regexp.MustCompile(`^caller=.+?:[0-9]+ msg="caller tracked event"$`)
		if !callerRegex.MatchString(out) {
			return fmt.Errorf("assertion 3 failed: output %q did not match caller pattern", out)
		}
	}

	// 4. log.MessageKey, log.TimestampKey, and log.FileKey configure custom field names for extracted data
	{
		buf.Reset()
		adapter := log.NewStdlibAdapter(baseLogger,
			log.MessageKey("log_message"),
			log.TimestampKey("log_time"),
			log.FileKey("log_source"),
		)
		l := stdlog.New(adapter, "", stdlog.Ldate|stdlog.Ltime|stdlog.Lshortfile)
		l.Print("customized key event")

		out := strings.TrimSpace(buf.String())
		customRegex := regexp.MustCompile(`^log_time="[0-9]{4}/[0-9]{2}/[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}" log_source=.+?:[0-9]+ log_message="customized key event"$`)
		if !customRegex.MatchString(out) {
			return fmt.Errorf("assertion 4 failed: output %q did not match custom keys pattern", out)
		}
	}

	// 5. log.Prefix strips standard library prefixes or retains them when joinPrefixToMsg is true
	{
		// 5a. joinPrefixToMsg = false (prefix stripped)
		buf.Reset()
		adapterStrip := log.NewStdlibAdapter(baseLogger, log.Prefix("WORKER: ", false))
		lStrip := stdlog.New(adapterStrip, "WORKER: ", 0)
		lStrip.Print("task finished")

		out := strings.TrimSpace(buf.String())
		expected := `msg="task finished"`
		if out != expected {
			return fmt.Errorf("assertion 5a failed: expected %q, got %q", expected, out)
		}

		// 5b. joinPrefixToMsg = true (prefix joined)
		buf.Reset()
		adapterJoin := log.NewStdlibAdapter(baseLogger, log.Prefix("WORKER: ", true))
		lJoin := stdlog.New(adapterJoin, "WORKER: ", 0)
		lJoin.Print("task finished")

		out = strings.TrimSpace(buf.String())
		expectedJoin := `msg="WORKER: task finished"`
		if out != expectedJoin {
			return fmt.Errorf("assertion 5b failed: expected %q, got %q", expectedJoin, out)
		}
	}

	// 6. log.NewStdlibAdapter supports thread-safe concurrent writes from multiple goroutines
	{
		buf.Reset()
		syncLogger := log.NewSyncLogger(baseLogger)
		adapter := log.NewStdlibAdapter(syncLogger)
		l := stdlog.New(adapter, "", 0)

		const workerCount = 20
		var wg sync.WaitGroup
		for i := 0; i < workerCount; i++ {
			wg.Add(1)
			go func(id int) {
				defer wg.Done()
				l.Printf("worker %d completed", id)
			}(i)
		}
		wg.Wait()

		lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
		if len(lines) != workerCount {
			return fmt.Errorf("assertion 6 failed: expected %d lines, got %d", workerCount, len(lines))
		}
		for _, line := range lines {
			if !strings.HasPrefix(line, `msg="worker `) || !strings.HasSuffix(line, ` completed"`) {
				return fmt.Errorf("assertion 6 failed: unexpected line content %q", line)
			}
		}
	}

	return nil
}

Seeder de origen

anónimo