CodeSampleX

Exemple

github.com/sirupsen/logrus v1.6.0: JSONFormatter

Échantillon vérifié pour golang github.com/sirupsen/logrus v1.6.0: JSONFormatter. Le contrat s'est exécuté sur go 1.26 · linux debian/x64 · docker et a…

sha256:21cbf3a5d3f55fcc64a30ea1207f11bf733a52321cd23be4cb5d6de64b9bb4c1

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-05

Cas

HOW
Objectif
verify pkg:golang/github.com/sirupsen/logrus@v1.6.0
Paquets
Symboles
  • github.com/sirupsen/logrus.JSONFormatter
Créé
2026-09-05T02:00:36Z

Contrat

  1. logrus.JSONFormatter formats log entries into valid JSON with default keys level, msg, and time
  2. logrus.JSONFormatter.TimestampFormat formats entry timestamps using the specified layout string
  3. logrus.JSONFormatter.FieldMap remaps default keys to specified custom field names
  4. logrus.JSONFormatter.DataKey nests custom fields under a single parent key in output JSON
  5. logrus.JSONFormatter.PrettyPrint outputs indented multi-line JSON representation

Fichiers

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • sample.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 pkg:golang/github.com/sirupsen/logrus@v1.6.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/sirupsen/logrus@v1.6.0
Demonstrate these symbols/APIs:
  - github.com/sirupsen/logrus.JSONFormatter

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:1199f9e0195a5031af056a3f5579c08d0369eacca95c379c7652df3317159cfd","contract":["logrus.JSONFormatter formats log entries into valid JSON with default keys level, msg, and time","logrus.JSONFormatter.TimestampFormat formats entry timestamps using the specified layout string","logrus.JSONFormatter.FieldMap remaps default keys to specified custom field names","logrus.JSONFormatter.DataKey nests custom fields under a single parent key in output JSON","logrus.JSONFormatter.PrettyPrint outputs indented multi-line JSON representation"],"goal":"verify pkg:golang/github.com/sirupsen/logrus@v1.6.0","kind":"HOW","packages":["pkg:golang/github.com/sirupsen/logrus@v1.6.0"],"schemaVersion":1,"symbols":["github.com/sirupsen/logrus.JSONFormatter"]},"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/sirupsen/logrus@v1.6.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/sirupsen/logrus@v1.6.0","symbols":["github.com/sirupsen/logrus.JSONFormatter"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.22

require github.com/sirupsen/logrus v1.6.0

require (
	github.com/konsorten/go-windows-terminal-sequences v1.0.3 // indirect
	golang.org/x/sys v0.0.0-20190422165155-953cdadca894 // indirect
)
go.sum
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8=
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I=
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
sample.go
package sample

import (
	"bytes"
	"io"

	"github.com/sirupsen/logrus"
)

// NewJSONLogger creates a logrus.Logger configured with the provided JSONFormatter and output destination.
func NewJSONLogger(out io.Writer, formatter *logrus.JSONFormatter) *logrus.Logger {
	l := logrus.New()
	l.SetOutput(out)
	if formatter != nil {
		l.SetFormatter(formatter)
	} else {
		l.SetFormatter(&logrus.JSONFormatter{})
	}
	return l
}

// LogBuffer wraps a buffer and a JSON-configured logger for inspecting formatted output.
type LogBuffer struct {
	Buffer *bytes.Buffer
	Logger *logrus.Logger
}

// NewBufferedJSONLogger returns a logger writing JSON output to an in-memory buffer.
func NewBufferedJSONLogger(formatter *logrus.JSONFormatter) *LogBuffer {
	buf := new(bytes.Buffer)
	logger := NewJSONLogger(buf, formatter)
	return &LogBuffer{
		Buffer: buf,
		Logger: logger,
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/sirupsen/logrus@v1.6.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/sirupsen/logrus@v1.6.0"
  ],
  "symbols": [
    "github.com/sirupsen/logrus.JSONFormatter"
  ]
}
test/contract.go
package main

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/sirupsen/logrus"
	"sample"
)

func main() {
	// Assertion 1: logrus.JSONFormatter formats log entries into valid JSON with default keys level, msg, and time
	lb1 := sample.NewBufferedJSONLogger(&logrus.JSONFormatter{})
	lb1.Logger.WithField("user_id", 42).Info("user logged in")

	var parsed1 map[string]interface{}
	if err := json.Unmarshal(lb1.Buffer.Bytes(), &parsed1); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: output is not valid JSON: %v\n", err)
		os.Exit(1)
	}

	if parsed1["msg"] != "user logged in" {
		fmt.Fprintf(os.Stderr, "FAIL: expected msg 'user logged in', got %v\n", parsed1["msg"])
		os.Exit(1)
	}
	if parsed1["level"] != "info" {
		fmt.Fprintf(os.Stderr, "FAIL: expected level 'info', got %v\n", parsed1["level"])
		os.Exit(1)
	}
	if _, ok := parsed1["time"]; !ok {
		fmt.Fprintf(os.Stderr, "FAIL: expected time key in JSON output\n")
		os.Exit(1)
	}
	if val, ok := parsed1["user_id"].(float64); !ok || val != 42 {
		fmt.Fprintf(os.Stderr, "FAIL: expected user_id 42, got %v\n", parsed1["user_id"])
		os.Exit(1)
	}

	// Assertion 2: logrus.JSONFormatter.TimestampFormat formats entry timestamps using the specified layout string
	customTimeLayout := "2006-01-02 15:04:05"
	lb2 := sample.NewBufferedJSONLogger(&logrus.JSONFormatter{
		TimestampFormat: customTimeLayout,
	})
	lb2.Logger.Warn("scheduled maintenance")

	var parsed2 map[string]interface{}
	if err := json.Unmarshal(lb2.Buffer.Bytes(), &parsed2); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 2 invalid JSON: %v\n", err)
		os.Exit(1)
	}
	timeStr, ok := parsed2["time"].(string)
	if !ok {
		fmt.Fprintf(os.Stderr, "FAIL: expected string timestamp, got %T\n", parsed2["time"])
		os.Exit(1)
	}
	if _, err := time.Parse(customTimeLayout, timeStr); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: timestamp %q does not match layout %q: %v\n", timeStr, customTimeLayout, err)
		os.Exit(1)
	}

	// Assertion 3: logrus.JSONFormatter.FieldMap remaps default keys to specified custom field names
	lb3 := sample.NewBufferedJSONLogger(&logrus.JSONFormatter{
		FieldMap: logrus.FieldMap{
			logrus.FieldKeyMsg:   "message",
			logrus.FieldKeyLevel: "severity",
		},
	})
	lb3.Logger.Error("disk volume critical")

	var parsed3 map[string]interface{}
	if err := json.Unmarshal(lb3.Buffer.Bytes(), &parsed3); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 3 invalid JSON: %v\n", err)
		os.Exit(1)
	}
	if parsed3["message"] != "disk volume critical" {
		fmt.Fprintf(os.Stderr, "FAIL: expected remapped key 'message', got %v\n", parsed3["message"])
		os.Exit(1)
	}
	if parsed3["severity"] != "error" {
		fmt.Fprintf(os.Stderr, "FAIL: expected remapped key 'severity', got %v\n", parsed3["severity"])
		os.Exit(1)
	}
	if _, hasOldMsg := parsed3["msg"]; hasOldMsg {
		fmt.Fprintf(os.Stderr, "FAIL: output still contains original 'msg' key\n")
		os.Exit(1)
	}
	if _, hasOldLevel := parsed3["level"]; hasOldLevel {
		fmt.Fprintf(os.Stderr, "FAIL: output still contains original 'level' key\n")
		os.Exit(1)
	}

	// Assertion 4: logrus.JSONFormatter.DataKey nests custom fields under a single parent key in output JSON
	lb4 := sample.NewBufferedJSONLogger(&logrus.JSONFormatter{
		DataKey: "metadata",
	})
	lb4.Logger.WithFields(logrus.Fields{
		"client_ip": "127.0.0.1",
		"attempt":   3,
	}).Info("login retry")

	var parsed4 map[string]interface{}
	if err := json.Unmarshal(lb4.Buffer.Bytes(), &parsed4); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: assertion 4 invalid JSON: %v\n", err)
		os.Exit(1)
	}
	meta, ok := parsed4["metadata"].(map[string]interface{})
	if !ok {
		fmt.Fprintf(os.Stderr, "FAIL: expected 'metadata' to be an object, got %T\n", parsed4["metadata"])
		os.Exit(1)
	}
	if meta["client_ip"] != "127.0.0.1" {
		fmt.Fprintf(os.Stderr, "FAIL: expected metadata.client_ip '127.0.0.1', got %v\n", meta["client_ip"])
		os.Exit(1)
	}
	if val, ok := meta["attempt"].(float64); !ok || val != 3 {
		fmt.Fprintf(os.Stderr, "FAIL: expected metadata.attempt 3, got %v\n", meta["attempt"])
		os.Exit(1)
	}

	// Assertion 5: logrus.JSONFormatter.PrettyPrint outputs indented multi-line JSON representation
	lb5 := sample.NewBufferedJSONLogger(&logrus.JSONFormatter{
		PrettyPrint: true,
	})
	lb5.Logger.Info("debug print payload")

	output5 := lb5.Buffer.String()
	if !strings.Contains(output5, "\n  \"") {
		fmt.Fprintf(os.Stderr, "FAIL: expected pretty-printed indentation, got:\n%s\n", output5)
		os.Exit(1)
	}

	fmt.Println("PASS: all logrus JSONFormatter contract assertions passed")
}

Seeder d'origine

anonyme