CodeSampleX

サンプル

go.opentelemetry.io/otel/log v1.47.0

検証済みサンプル — golang go.opentelemetry.io/otel/log v1.47.0. go 1.26 · linux debian/x64 · docker で contract を実行し、成功しました: Record constructs with timestamp…

sha256:ccc3539b741ca059aed13d3757c68055ad4a9b0d39c103537632b5e5e83f1e4e

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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-10-10

ケース

HOW
ゴール
verify pkg:golang/go.opentelemetry.io/otel/log@v1.47.0
パッケージ
作成日
2026-10-10T18:36:18Z

コントラクト

  1. Record constructs with timestamp, observed timestamp, severity, severity text, event name, and body
  2. Record adds and extracts typed KeyValue attributes for string, int, bool, and float
  3. Record supports attribute inspection via WalkAttributes and AttributesLen
  4. Record Clone creates an independent copy preserving attributes and severity
  5. LoggerProvider creates a Logger that emits log records and evaluates Enabled

ファイル

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • log.go
  • spec.json
  • test/contract_test.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/go.opentelemetry.io/otel/log@v1.47.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.opentelemetry.io/otel/log@v1.47.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:d1d1eee1ddbd146cf96c3452cb5627dc9f4334a0bd14b82b0c004cfe641f287f","contract":["Record constructs with timestamp, observed timestamp, severity, severity text, event name, and body","Record adds and extracts typed KeyValue attributes for string, int, bool, and float","Record supports attribute inspection via WalkAttributes and AttributesLen","Record Clone creates an independent copy preserving attributes and severity","LoggerProvider creates a Logger that emits log records and evaluates Enabled"],"goal":"verify pkg:golang/go.opentelemetry.io/otel/log@v1.47.0","kind":"HOW","packages":["pkg:golang/go.opentelemetry.io/otel/log@v1.47.0"],"schemaVersion":1},"contractCommand":["go","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/go.opentelemetry.io/otel/log@v1.47.0"],"schemaVersion":1,"subject":"pkg:golang/go.opentelemetry.io/otel/log@v1.47.0","verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require (
	go.opentelemetry.io/otel v1.47.0
	go.opentelemetry.io/otel/log v1.47.0
)

require github.com/cespare/xxhash/v2 v2.3.0 // indirect
go.sum
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI=
go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
log.go
package sample

import (
	"context"
	"time"

	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/log"
	"go.opentelemetry.io/otel/log/noop"
)

// LogEvent represents structured application log event data.
type LogEvent struct {
	Timestamp   time.Time
	Severity    log.Severity
	SeverityTxt string
	EventName   string
	Message     string
	Attributes  []attribute.KeyValue
}

// BuildRecord constructs a log.Record from a LogEvent.
func BuildRecord(ev LogEvent) log.Record {
	var r log.Record
	if !ev.Timestamp.IsZero() {
		r.SetTimestamp(ev.Timestamp)
		r.SetObservedTimestamp(ev.Timestamp)
	}
	r.SetSeverity(ev.Severity)
	r.SetSeverityText(ev.SeverityTxt)
	r.SetEventName(ev.EventName)
	r.SetBody(attribute.StringValue(ev.Message))
	if len(ev.Attributes) > 0 {
		r.AddAttributes(ev.Attributes...)
	}
	return r
}

// ExtractAttributes collects attributes from a log.Record into a map.
func ExtractAttributes(r *log.Record) map[string]attribute.Value {
	attrs := make(map[string]attribute.Value, r.AttributesLen())
	r.WalkAttributes(func(kv attribute.KeyValue) bool {
		attrs[string(kv.Key)] = kv.Value
		return true
	})
	return attrs
}

// NewNoopLogger creates a Logger using noop.NewLoggerProvider.
func NewNoopLogger(name, version string) log.Logger {
	provider := noop.NewLoggerProvider()
	return provider.Logger(name, log.WithInstrumentationVersion(version))
}

// EmitLog safely emits a record to the provided logger.
func EmitLog(ctx context.Context, logger log.Logger, r log.Record) {
	if logger != nil {
		logger.Emit(ctx, r)
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/go.opentelemetry.io/otel/log@v1.47.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.opentelemetry.io/otel/log@v1.47.0"
  ]
}
test/contract_test.go
package test

import (
	"context"
	"errors"
	"testing"
	"time"

	sample "sample"

	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/log"
)

func TestContractRecord(t *testing.T) {
	now := time.Date(2026, 10, 10, 12, 0, 0, 0, time.UTC)
	event := sample.LogEvent{
		Timestamp:   now,
		Severity:    log.SeverityInfo,
		SeverityTxt: "INFO",
		EventName:   "user.login",
		Message:     "user logged in successfully",
		Attributes: []attribute.KeyValue{
			attribute.String("user.id", "usr_99"),
			attribute.Int("attempt", 1),
			attribute.Bool("success", true),
			attribute.Float64("duration_ms", 12.5),
		},
	}

	record := sample.BuildRecord(event)

	// 1. Record constructs with timestamp, observed timestamp, severity, severity text, event name, and body
	if !record.Timestamp().Equal(now) {
		t.Fatalf("expected timestamp %v, got %v", now, record.Timestamp())
	}
	if !record.ObservedTimestamp().Equal(now) {
		t.Fatalf("expected observed timestamp %v, got %v", now, record.ObservedTimestamp())
	}
	if record.Severity() != log.SeverityInfo {
		t.Fatalf("expected severity %v, got %v", log.SeverityInfo, record.Severity())
	}
	if record.SeverityText() != "INFO" {
		t.Fatalf("expected severity text INFO, got %s", record.SeverityText())
	}
	if record.EventName() != "user.login" {
		t.Fatalf("expected event name user.login, got %s", record.EventName())
	}
	if record.Body().AsString() != "user logged in successfully" {
		t.Fatalf("expected body match, got %s", record.Body().AsString())
	}

	// 2. Record adds and extracts typed KeyValue attributes for string, int, bool, and float
	if record.AttributesLen() != 4 {
		t.Fatalf("expected 4 attributes, got %d", record.AttributesLen())
	}
	attrs := sample.ExtractAttributes(&record)
	if attrs["user.id"].AsString() != "usr_99" {
		t.Fatalf("expected user.id usr_99, got %s", attrs["user.id"].AsString())
	}
	if attrs["attempt"].AsInt64() != 1 {
		t.Fatalf("expected attempt 1, got %d", attrs["attempt"].AsInt64())
	}
	if !attrs["success"].AsBool() {
		t.Fatalf("expected success true, got %v", attrs["success"].AsBool())
	}
	if attrs["duration_ms"].AsFloat64() != 12.5 {
		t.Fatalf("expected duration 12.5, got %f", attrs["duration_ms"].AsFloat64())
	}

	// 3. Record supports attribute inspection via WalkAttributes and AttributesLen
	walked := 0
	record.WalkAttributes(func(kv attribute.KeyValue) bool {
		walked++
		return true
	})
	if walked != 4 {
		t.Fatalf("expected WalkAttributes to walk 4 items, walked %d", walked)
	}

	// 4. Record Clone creates an independent copy preserving attributes and severity
	cloned := record.Clone()
	cloned.SetSeverity(log.SeverityError)
	cloned.SetSeverityText("ERROR")
	cloned.SetErr(errors.New("test error"))
	cloned.AddAttributes(attribute.String("extra", "val"))

	if record.Severity() != log.SeverityInfo {
		t.Fatalf("original severity mutated: got %v, want %v", record.Severity(), log.SeverityInfo)
	}
	if record.AttributesLen() != 4 {
		t.Fatalf("original attributes mutated: got %d, want 4", record.AttributesLen())
	}
	if record.Err() != nil {
		t.Fatalf("original err mutated: got %v, want nil", record.Err())
	}
	if cloned.Severity() != log.SeverityError {
		t.Fatalf("cloned severity mismatch: got %v, want %v", cloned.Severity(), log.SeverityError)
	}
	if cloned.AttributesLen() != 5 {
		t.Fatalf("cloned attributes len mismatch: got %d, want 5", cloned.AttributesLen())
	}
	if cloned.Err() == nil {
		t.Fatal("expected cloned err to be non-nil")
	}

	// 5. LoggerProvider creates a Logger that emits log records and evaluates Enabled
	ctx := context.Background()
	logger := sample.NewNoopLogger("test-logger", "1.0.0")
	if logger == nil {
		t.Fatal("expected non-nil logger")
	}
	enabled := logger.Enabled(ctx, log.EnabledParameters{})
	_ = enabled
	sample.EmitLog(ctx, logger, record)
	sample.EmitLog(ctx, logger, cloned)
}

オリジンシーダー

匿名