CodeSampleX

Exemple

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

Échantillon vérifié pour golang github.com/go-kit/log v0.1.0: NewJSONLogger. Le contrat s'est exécuté sur go 1.26 · linux debian/x64 · docker et a réussi.

sha256:0dcfa01ee9c57bb5e5840427acb798717cf6f61dd6ab05450a0a34c2155f8524

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 go

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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

Cas

HOW
Objectif
verify github.com/go-kit/log.NewJSONLogger in pkg:golang/github.com/go-kit/log@v0.1.0
Paquets
Symboles
  • github.com/go-kit/log.NewJSONLogger
Créé
2026-09-04T02:18:30Z

Contrat

  1. log.NewJSONLogger encodes key-value pairs into valid newline-delimited JSON objects
  2. log.NewJSONLogger includes contextual keyvals when decorated with log.With
  3. log.NewJSONLogger pairs an odd trailing key with the (MISSING) value sentinel
  4. log.NewJSONLogger propagates write errors encountered by the underlying io.Writer
  5. log.NewJSONLogger supports leveled logging through level.NewFilter

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

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-kit/log.NewJSONLogger in 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
Demonstrate these symbols/APIs:
  - github.com/go-kit/log.NewJSONLogger

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:ac98f5d987942a68a84d3320aa608c71032dfc18e7bace261a9608238358cd67","contract":["log.NewJSONLogger encodes key-value pairs into valid newline-delimited JSON objects","log.NewJSONLogger includes contextual keyvals when decorated with log.With","log.NewJSONLogger pairs an odd trailing key with the (MISSING) value sentinel","log.NewJSONLogger propagates write errors encountered by the underlying io.Writer","log.NewJSONLogger supports leveled logging through level.NewFilter"],"goal":"verify github.com/go-kit/log.NewJSONLogger in 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":["github.com/go-kit/log.NewJSONLogger"]},"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":["github.com/go-kit/log.NewJSONLogger"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.22.0

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=
logger.go
package sample

import (
	"io"

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

// NewEventLogger returns a go-kit Logger that formats log events as JSON objects.
func NewEventLogger(w io.Writer) log.Logger {
	return log.NewJSONLogger(w)
}

// NewContextLogger creates a JSON logger with preset contextual key-value pairs.
func NewContextLogger(w io.Writer, keyvals ...interface{}) log.Logger {
	logger := log.NewJSONLogger(w)
	return log.With(logger, keyvals...)
}

// NewLeveledLogger returns a JSON logger configured with a level filter.
func NewLeveledLogger(w io.Writer, minLevel string) log.Logger {
	logger := log.NewJSONLogger(w)
	var opt level.Option
	switch minLevel {
	case "debug":
		opt = level.AllowDebug()
	case "info":
		opt = level.AllowInfo()
	case "warn":
		opt = level.AllowWarn()
	case "error":
		opt = level.AllowError()
	default:
		opt = level.AllowAll()
	}
	return level.NewFilter(logger, opt)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/go-kit/log.NewJSONLogger in pkg:golang/github.com/go-kit/log@v0.1.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/go-kit/log@v0.1.0"
  ],
  "symbols": [
    "github.com/go-kit/log.NewJSONLogger"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"os"

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

type failingWriter struct{}

func (failingWriter) Write(p []byte) (int, error) {
	return 0, io.ErrShortWrite
}

func main() {
	// Assertion 1: log.NewJSONLogger encodes key-value pairs into valid newline-delimited JSON objects
	var buf1 bytes.Buffer
	logger1 := sample.NewEventLogger(&buf1)
	if err := logger1.Log("msg", "hello", "count", 42); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: logger.Log returned error: %v\n", err)
		os.Exit(1)
	}
	output1 := buf1.String()
	if len(output1) == 0 || output1[len(output1)-1] != '\n' {
		fmt.Fprintf(os.Stderr, "FAIL: expected newline at end of log output, got %q\n", output1)
		os.Exit(1)
	}
	var data1 map[string]interface{}
	if err := json.Unmarshal(buf1.Bytes(), &data1); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: invalid JSON emitted: %v\n", err)
		os.Exit(1)
	}
	if data1["msg"] != "hello" || data1["count"] != float64(42) {
		fmt.Fprintf(os.Stderr, "FAIL: unexpected log content: %+v\n", data1)
		os.Exit(1)
	}

	// Assertion 2: log.NewJSONLogger includes contextual keyvals when decorated with log.With
	var buf2 bytes.Buffer
	logger2 := sample.NewContextLogger(&buf2, "service", "payment-service", "env", "production")
	if err := logger2.Log("action", "charge", "amount", 99.5); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: contextual logger.Log returned error: %v\n", err)
		os.Exit(1)
	}
	var data2 map[string]interface{}
	if err := json.Unmarshal(buf2.Bytes(), &data2); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: invalid JSON in contextual log: %v\n", err)
		os.Exit(1)
	}
	if data2["service"] != "payment-service" || data2["env"] != "production" || data2["action"] != "charge" || data2["amount"] != 99.5 {
		fmt.Fprintf(os.Stderr, "FAIL: contextual fields mismatch: %+v\n", data2)
		os.Exit(1)
	}

	// Assertion 3: log.NewJSONLogger pairs an odd trailing key with the (MISSING) value sentinel
	var buf3 bytes.Buffer
	logger3 := log.NewJSONLogger(&buf3)
	if err := logger3.Log("keyA", "valA", "unpairedKey"); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: odd keyvals logger.Log error: %v\n", err)
		os.Exit(1)
	}
	var data3 map[string]interface{}
	if err := json.Unmarshal(buf3.Bytes(), &data3); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: invalid JSON in odd keyvals log: %v\n", err)
		os.Exit(1)
	}
	if data3["keyA"] != "valA" || data3["unpairedKey"] != "(MISSING)" {
		fmt.Fprintf(os.Stderr, "FAIL: odd keyval sentinel mismatch: %+v\n", data3)
		os.Exit(1)
	}

	// Assertion 4: log.NewJSONLogger propagates write errors encountered by the underlying io.Writer
	logger4 := log.NewJSONLogger(failingWriter{})
	if err := logger4.Log("status", "error"); err != io.ErrShortWrite {
		fmt.Fprintf(os.Stderr, "FAIL: expected io.ErrShortWrite, got %v\n", err)
		os.Exit(1)
	}

	// Assertion 5: log.NewJSONLogger supports leveled logging through level.NewFilter
	var buf5 bytes.Buffer
	logger5 := sample.NewLeveledLogger(&buf5, "info")
	if err := level.Debug(logger5).Log("debug_event", "should_be_suppressed"); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: level.Debug returned error: %v\n", err)
		os.Exit(1)
	}
	if buf5.Len() != 0 {
		fmt.Fprintf(os.Stderr, "FAIL: expected debug log to be filtered out, got %q\n", buf5.String())
		os.Exit(1)
	}
	if err := level.Info(logger5).Log("info_event", "delivered"); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: level.Info returned error: %v\n", err)
		os.Exit(1)
	}
	var data5 map[string]interface{}
	if err := json.Unmarshal(buf5.Bytes(), &data5); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: invalid JSON in info log: %v\n", err)
		os.Exit(1)
	}
	if data5["level"] != "info" || data5["info_event"] != "delivered" {
		fmt.Fprintf(os.Stderr, "FAIL: info log data mismatch: %+v\n", data5)
		os.Exit(1)
	}

	fmt.Println("PASS: github.com/go-kit/log.NewJSONLogger contract passed")
}

Seeder d'origine

anonyme