CodeSampleX

Пример

github.com/go-kit/log v0.1.0: NewLogfmtLogger, NewJSONLogger, With

Проверенный пример — golang github.com/go-kit/log v0.1.0: NewLogfmtLogger, NewJSONLogger, With. Контракт выполнен на go 1.26 · linux debian/x64 · docker и…

sha256:f06b182c96dd4261a1f48e393fb359874eb670ac45c4b19bef87dfbe6ff1e849

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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-03

Кейс

HOW
Цель
verify pkg:golang/github.com/go-kit/log@v0.1.0
Пакеты
Символы
  • log.NewLogfmtLogger
  • log.NewJSONLogger
  • log.With
  • log.Timestamp
  • level.NewFilter
  • log.NewSyncLogger
Создан
2026-09-03T17:45:57Z

Контракт

  1. log.NewLogfmtLogger formats structured key-value pairs into logfmt strings
  2. log.NewJSONLogger formats structured key-value pairs as valid JSON lines
  3. log.With preserves contextual key-value pairs across log invocations
  4. log.Timestamp dynamically evaluates timestamp Valuers on each log call
  5. level.NewFilter squelches debug messages and allows info and error messages
  6. log.NewSyncLogger provides thread-safe structured logging across concurrent goroutines

Файлы

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • 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-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:bee5e401b0ef696bdd6e3020cbf7fa82e4a151d956f6b4f3f3e687ec122ecd66","contract":["log.NewLogfmtLogger formats structured key-value pairs into logfmt strings","log.NewJSONLogger formats structured key-value pairs as valid JSON lines","log.With preserves contextual key-value pairs across log invocations","log.Timestamp dynamically evaluates timestamp Valuers on each log call","level.NewFilter squelches debug messages and allows info and error messages","log.NewSyncLogger provides thread-safe structured logging across concurrent 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.NewLogfmtLogger","log.NewJSONLogger","log.With","log.Timestamp","level.NewFilter","log.NewSyncLogger"]},"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.NewLogfmtLogger","log.NewJSONLogger","log.With","log.Timestamp","level.NewFilter","log.NewSyncLogger"],"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"
	"encoding/json"
	"errors"
	"fmt"
	"os"
	"strings"
	"sync"
	"time"

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

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

func runTests() error {
	// 1. Test log.NewLogfmtLogger formats structured key-value pairs into logfmt strings
	var buf bytes.Buffer
	logger := log.NewLogfmtLogger(&buf)
	if err := logger.Log("msg", "task completed", "code", 200, "active", true); err != nil {
		return fmt.Errorf("logfmt logger.Log failed: %w", err)
	}
	out := strings.TrimSpace(buf.String())
	if out != `msg="task completed" code=200 active=true` {
		return fmt.Errorf("unexpected logfmt output: %q", out)
	}

	// 2. Test log.NewJSONLogger formats structured key-value pairs as valid JSON lines
	buf.Reset()
	jsonLogger := log.NewJSONLogger(&buf)
	if err := jsonLogger.Log("msg", "start processing", "retries", 3); err != nil {
		return fmt.Errorf("json logger.Log failed: %w", err)
	}
	var data map[string]interface{}
	if err := json.Unmarshal(buf.Bytes(), &data); err != nil {
		return fmt.Errorf("json unmarshal failed: %w (output: %q)", err, buf.String())
	}
	if data["msg"] != "start processing" || data["retries"] != float64(3) {
		return fmt.Errorf("unexpected json output: %+v", data)
	}

	// 3. Test log.With preserves contextual key-value pairs across log invocations
	buf.Reset()
	ctxLogger := log.With(logger, "component", "indexer", "version", "1.0")
	if err := ctxLogger.Log("status", "ready"); err != nil {
		return fmt.Errorf("contextual logger.Log failed: %w", err)
	}
	out = strings.TrimSpace(buf.String())
	if out != `component=indexer version=1.0 status=ready` {
		return fmt.Errorf("unexpected contextual logfmt output: %q", out)
	}

	// 4. Test log.Timestamp dynamically evaluates timestamp Valuers on each log call
	buf.Reset()
	fixedTime := time.Date(2026, 9, 3, 12, 0, 0, 0, time.UTC)
	timeValuer := log.Timestamp(func() time.Time {
		return fixedTime
	})
	valLogger := log.With(logger, "ts", timeValuer)
	if err := valLogger.Log("msg", "event logged"); err != nil {
		return fmt.Errorf("valuer logger.Log failed: %w", err)
	}
	out = strings.TrimSpace(buf.String())
	if out != `ts=2026-09-03T12:00:00Z msg="event logged"` {
		return fmt.Errorf("unexpected valuer output: %q", out)
	}

	// 5. Test level.NewFilter squelches debug messages and allows info and error messages
	buf.Reset()
	filterLogger := level.NewFilter(logger, level.AllowInfo())

	// Debug should be squelched
	if err := level.Debug(filterLogger).Log("msg", "debugging"); err != nil {
		return fmt.Errorf("level.Debug failed: %w", err)
	}
	if buf.Len() != 0 {
		return fmt.Errorf("expected debug log to be squelched, got: %q", buf.String())
	}

	// Info should be emitted
	if err := level.Info(filterLogger).Log("msg", "info notification"); err != nil {
		return fmt.Errorf("level.Info failed: %w", err)
	}
	out = strings.TrimSpace(buf.String())
	if out != `level=info msg="info notification"` {
		return fmt.Errorf("unexpected level.Info output: %q", out)
	}

	// Error should be emitted
	buf.Reset()
	if err := level.Error(filterLogger).Log("msg", "failure detected", "err", errors.New("timeout")); err != nil {
		return fmt.Errorf("level.Error failed: %w", err)
	}
	out = strings.TrimSpace(buf.String())
	if out != `level=error msg="failure detected" err=timeout` {
		return fmt.Errorf("unexpected level.Error output: %q", out)
	}

	// 6. Test log.NewSyncLogger provides thread-safe structured logging across concurrent goroutines
	buf.Reset()
	syncLogger := log.NewSyncLogger(logger)
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()
			_ = syncLogger.Log("worker_id", id, "done", true)
		}(i)
	}
	wg.Wait()
	lines := strings.Split(strings.TrimSpace(buf.String()), "\n")
	if len(lines) != 10 {
		return fmt.Errorf("expected 10 lines from concurrent workers, got %d", len(lines))
	}

	return nil
}

Исходный сидер

аноним