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, observed…

sha256:ccc3539b741ca059aed13d3757c68055ad4a9b0d39c103537632b5e5e83f1e4e

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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)
}

오리진 시더

익명