CodeSampleX

Ejemplo

go.opentelemetry.io/proto/otlp v1.10.0: build and serialize LogsData with ResourceLogs and LogRecord

Muestra verificada para golang go.opentelemetry.io/proto/otlp v1.10.0: build and serialize LogsData with ResourceLogs and LogRecord. El contrato se ejecutó…

sha256:e89fc8e889820bdb6b5bf8d142742382d40878b8880b1efe20b56f9c320695cf

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado go linux 24 · ubuntu · glibc 2.39 x64 go go

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-28

Caso

HOW
Objetivo
build and serialize LogsData with ResourceLogs and LogRecord
Paquetes
Símbolos
  • go.opentelemetry.io/proto/otlp/logs/v1.LogsData
Entorno
go
Creado
2026-08-28T13:21:31Z

Contrato

  1. LogsData constructs and holds valid ResourceLogs with Resource, ScopeLogs, and LogRecords
  2. LogsData marshals to and unmarshals from binary protobuf wire format without data loss
  3. LogsData marshals to and unmarshals from JSON format preserving log attributes and metadata
  4. LogsData preserves trace ID and span ID correlation byte sequences across serialization
  5. LogsData preserves log severity number, severity text, observed timestamps, and body payload across serialization
  6. LogsData handles multiple ResourceLogs with multiple ScopeLogs and multiple LogRecords

Archivos

  • PROMPT.md
  • contract_test.go
  • csx.json
  • go.mod
  • go.sum
  • sample.go
  • spec.json

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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: build and serialize LogsData with ResourceLogs and LogRecord
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.opentelemetry.io/proto/otlp@v1.10.0
Demonstrate these symbols/APIs:
  - go.opentelemetry.io/proto/otlp/logs/v1.LogsData

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

import (
	"bytes"
	"strings"
	"testing"

	logspb "go.opentelemetry.io/proto/otlp/logs/v1"
)

func TestLogsDataContract(t *testing.T) {
	traceID := [16]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10}
	spanID := [8]byte{0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}

	// 1. LogsData constructs and holds valid ResourceLogs with Resource, ScopeLogs, and LogRecords
	t.Run("ConstructValidLogsData", func(t *testing.T) {
		record1 := NewLogRecord(
			traceID,
			spanID,
			1700000000000000000,
			1700000000100000000,
			logspb.SeverityNumber_SEVERITY_NUMBER_INFO,
			"INFO",
			"User authenticated successfully",
			StringAttribute("user.id", "usr-1234"),
			IntAttribute("attempt.count", 1),
			BoolAttribute("mfa.enabled", true),
			DoubleAttribute("duration_ms", 12.34),
			BytesAttribute("session.hash", []byte{0xde, 0xad, 0xbe, 0xef}),
		)
		resLogs1 := NewResourceLogs("auth-service", "sample/logger", "1.0.0", []*logspb.LogRecord{record1})
		logsData := NewLogsData(resLogs1)

		if len(logsData.GetResourceLogs()) != 1 {
			t.Fatalf("expected 1 ResourceLogs, got %d", len(logsData.GetResourceLogs()))
		}
		rl := logsData.GetResourceLogs()[0]
		if rl.GetResource() == nil || len(rl.GetResource().GetAttributes()) == 0 {
			t.Fatalf("expected resource attributes to be present")
		}
		if rl.GetResource().GetAttributes()[0].GetKey() != "service.name" ||
			rl.GetResource().GetAttributes()[0].GetValue().GetStringValue() != "auth-service" {
			t.Fatalf("unexpected resource attribute: %v", rl.GetResource().GetAttributes()[0])
		}
		if len(rl.GetScopeLogs()) != 1 {
			t.Fatalf("expected 1 ScopeLogs, got %d", len(rl.GetScopeLogs()))
		}
		sl := rl.GetScopeLogs()[0]
		if sl.GetScope().GetName() != "sample/logger" || sl.GetScope().GetVersion() != "1.0.0" {
			t.Fatalf("unexpected scope: %v", sl.GetScope())
		}
		if len(sl.GetLogRecords()) != 1 {
			t.Fatalf("expected 1 LogRecord, got %d", len(sl.GetLogRecords()))
		}
	})

	// 2. LogsData marshals to and unmarshals from binary protobuf wire format without data loss
	// 4. LogsData preserves trace ID and span ID correlation byte sequences across serialization
	// 5. LogsData preserves log severity number, severity text, observed timestamps, and body payload across serialization
	t.Run("ProtobufSerializationRoundtrip", func(t *testing.T) {
		record1 := NewLogRecord(
			traceID,
			spanID,
			1700000000000000000,
			1700000000100000000,
			logspb.SeverityNumber_SEVERITY_NUMBER_INFO,
			"INFO",
			"User authenticated successfully",
			StringAttribute("user.id", "usr-1234"),
			IntAttribute("attempt.count", 1),
		)
		resLogs1 := NewResourceLogs("auth-service", "sample/logger", "1.0.0", []*logspb.LogRecord{record1})
		logsData := NewLogsData(resLogs1)

		data, err := MarshalProto(logsData)
		if err != nil {
			t.Fatalf("failed to marshal logs data to protobuf: %v", err)
		}
		if len(data) == 0 {
			t.Fatalf("marshaled protobuf wire format is empty")
		}
		unmarshaledLogs, err := UnmarshalProto(data)
		if err != nil {
			t.Fatalf("failed to unmarshal logs data from protobuf: %v", err)
		}
		if len(unmarshaledLogs.GetResourceLogs()) != 1 {
			t.Fatalf("unmarshaled logs data missing ResourceLogs")
		}
		uRecord := unmarshaledLogs.GetResourceLogs()[0].GetScopeLogs()[0].GetLogRecords()[0]
		if uRecord.GetBody().GetStringValue() != "User authenticated successfully" {
			t.Fatalf("unmarshaled body mismatch: got %q, want 'User authenticated successfully'", uRecord.GetBody().GetStringValue())
		}

		if !bytes.Equal(uRecord.GetTraceId(), traceID[:]) {
			t.Fatalf("trace ID mismatch after proto roundtrip: got %x, want %x", uRecord.GetTraceId(), traceID)
		}
		if !bytes.Equal(uRecord.GetSpanId(), spanID[:]) {
			t.Fatalf("span ID mismatch after proto roundtrip: got %x, want %x", uRecord.GetSpanId(), spanID)
		}
		if uRecord.GetSeverityNumber() != logspb.SeverityNumber_SEVERITY_NUMBER_INFO {
			t.Fatalf("severity number mismatch: got %v, want %v", uRecord.GetSeverityNumber(), logspb.SeverityNumber_SEVERITY_NUMBER_INFO)
		}
		if uRecord.GetSeverityText() != "INFO" {
			t.Fatalf("severity text mismatch: got %q, want 'INFO'", uRecord.GetSeverityText())
		}
		if uRecord.GetTimeUnixNano() != 1700000000000000000 {
			t.Fatalf("timeUnixNano mismatch: got %d, want 1700000000000000000", uRecord.GetTimeUnixNano())
		}
		if uRecord.GetObservedTimeUnixNano() != 1700000000100000000 {
			t.Fatalf("observedTimeUnixNano mismatch: got %d, want 1700000000100000000", uRecord.GetObservedTimeUnixNano())
		}
	})

	// 3. LogsData marshals to and unmarshals from JSON format preserving log attributes and metadata
	t.Run("JSONSerializationRoundtrip", func(t *testing.T) {
		record1 := NewLogRecord(
			traceID,
			spanID,
			1700000000000000000,
			1700000000100000000,
			logspb.SeverityNumber_SEVERITY_NUMBER_INFO,
			"INFO",
			"User authenticated successfully",
			StringAttribute("user.id", "usr-1234"),
		)
		resLogs1 := NewResourceLogs("auth-service", "sample/logger", "1.0.0", []*logspb.LogRecord{record1})
		logsData := NewLogsData(resLogs1)

		jsonData, err := MarshalJSON(logsData)
		if err != nil {
			t.Fatalf("failed to marshal logs data to JSON: %v", err)
		}
		if !strings.Contains(string(jsonData), "auth-service") || !strings.Contains(string(jsonData), "User authenticated successfully") {
			t.Fatalf("JSON output missing expected fields: %s", string(jsonData))
		}
		jsonLogs, err := UnmarshalJSON(jsonData)
		if err != nil {
			t.Fatalf("failed to unmarshal logs data from JSON: %v", err)
		}
		if len(jsonLogs.GetResourceLogs()) != 1 {
			t.Fatalf("JSON unmarshaled logs data missing ResourceLogs")
		}
		jsonRecord := jsonLogs.GetResourceLogs()[0].GetScopeLogs()[0].GetLogRecords()[0]
		if jsonRecord.GetSeverityText() != "INFO" {
			t.Fatalf("JSON unmarshaled severity text mismatch: got %q, want 'INFO'", jsonRecord.GetSeverityText())
		}
	})

	// 6. LogsData handles multiple ResourceLogs with multiple ScopeLogs and multiple LogRecords
	t.Run("MultipleResourceLogsHandling", func(t *testing.T) {
		multiLogs := NewLogsData(
			NewResourceLogs("billing-service", "sample/billing", "2.0.0", []*logspb.LogRecord{
				NewLogRecord([16]byte{1}, [8]byte{1}, 100, 101, logspb.SeverityNumber_SEVERITY_NUMBER_WARN, "WARN", "Invoice payment pending"),
				NewLogRecord([16]byte{2}, [8]byte{2}, 200, 201, logspb.SeverityNumber_SEVERITY_NUMBER_ERROR, "ERROR", "Payment gateway timeout"),
			}),
			NewResourceLogs("order-service", "sample/orders", "1.5.0", []*logspb.LogRecord{
				NewLogRecord([16]byte{3}, [8]byte{3}, 300, 301, logspb.SeverityNumber_SEVERITY_NUMBER_DEBUG, "DEBUG", "Order cart validated"),
			}),
		)
		multiData, err := MarshalProto(multiLogs)
		if err != nil {
			t.Fatalf("failed to marshal multi-resource logs: %v", err)
		}
		multiUnmarshaled, err := UnmarshalProto(multiData)
		if err != nil {
			t.Fatalf("failed to unmarshal multi-resource logs: %v", err)
		}
		if len(multiUnmarshaled.GetResourceLogs()) != 2 {
			t.Fatalf("expected 2 ResourceLogs, got %d", len(multiUnmarshaled.GetResourceLogs()))
		}
		if len(multiUnmarshaled.GetResourceLogs()[0].GetScopeLogs()[0].GetLogRecords()) != 2 {
			t.Fatalf("expected 2 LogRecords in first ResourceLogs, got %d", len(multiUnmarshaled.GetResourceLogs()[0].GetScopeLogs()[0].GetLogRecords()))
		}
		if len(multiUnmarshaled.GetResourceLogs()[1].GetScopeLogs()[0].GetLogRecords()) != 1 {
			t.Fatalf("expected 1 LogRecord in second ResourceLogs, got %d", len(multiUnmarshaled.GetResourceLogs()[1].GetScopeLogs()[0].GetLogRecords()))
		}
	})
}
csx.json
{"case":{"caseId":"case:sha256:1e5f60be48dfa14810b669a3315cfe4e9fe8b240195c7f1ad37d1c4cd7f5d6e7","contract":["LogsData constructs and holds valid ResourceLogs with Resource, ScopeLogs, and LogRecords","LogsData marshals to and unmarshals from binary protobuf wire format without data loss","LogsData marshals to and unmarshals from JSON format preserving log attributes and metadata","LogsData preserves trace ID and span ID correlation byte sequences across serialization","LogsData preserves log severity number, severity text, observed timestamps, and body payload across serialization","LogsData handles multiple ResourceLogs with multiple ScopeLogs and multiple LogRecords"],"goal":"build and serialize LogsData with ResourceLogs and LogRecord","kind":"HOW","packages":["pkg:golang/go.opentelemetry.io/proto/otlp@v1.10.0"],"schemaVersion":1,"symbols":["go.opentelemetry.io/proto/otlp/logs/v1.LogsData"]},"contractCommand":["go","test","-mod=readonly","-count=1","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","executionContext":"go","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/go.opentelemetry.io/proto/otlp@v1.10.0"],"schemaVersion":1,"subject":"pkg:golang/go.opentelemetry.io/proto/otlp@v1.10.0","symbols":["go.opentelemetry.io/proto/otlp/logs/v1.LogsData"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require (
	go.opentelemetry.io/proto/otlp v1.10.0
	google.golang.org/protobuf v1.36.11
)
go.sum
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=
go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
sample.go
package sample

import (
	commonpb "go.opentelemetry.io/proto/otlp/common/v1"
	logspb "go.opentelemetry.io/proto/otlp/logs/v1"
	resourcepb "go.opentelemetry.io/proto/otlp/resource/v1"
	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/proto"
)

// StringAttribute creates a string KeyValue attribute.
func StringAttribute(key, value string) *commonpb.KeyValue {
	return &commonpb.KeyValue{
		Key: key,
		Value: &commonpb.AnyValue{
			Value: &commonpb.AnyValue_StringValue{
				StringValue: value,
			},
		},
	}
}

// IntAttribute creates an int64 KeyValue attribute.
func IntAttribute(key string, value int64) *commonpb.KeyValue {
	return &commonpb.KeyValue{
		Key: key,
		Value: &commonpb.AnyValue{
			Value: &commonpb.AnyValue_IntValue{
				IntValue: value,
			},
		},
	}
}

// BoolAttribute creates a boolean KeyValue attribute.
func BoolAttribute(key string, value bool) *commonpb.KeyValue {
	return &commonpb.KeyValue{
		Key: key,
		Value: &commonpb.AnyValue{
			Value: &commonpb.AnyValue_BoolValue{
				BoolValue: value,
			},
		},
	}
}

// DoubleAttribute creates a float64 KeyValue attribute.
func DoubleAttribute(key string, value float64) *commonpb.KeyValue {
	return &commonpb.KeyValue{
		Key: key,
		Value: &commonpb.AnyValue{
			Value: &commonpb.AnyValue_DoubleValue{
				DoubleValue: value,
			},
		},
	}
}

// BytesAttribute creates a byte slice KeyValue attribute.
func BytesAttribute(key string, value []byte) *commonpb.KeyValue {
	return &commonpb.KeyValue{
		Key: key,
		Value: &commonpb.AnyValue{
			Value: &commonpb.AnyValue_BytesValue{
				BytesValue: value,
			},
		},
	}
}

// NewLogRecord constructs a LogRecord with metadata, body, and attributes.
func NewLogRecord(
	traceID [16]byte,
	spanID [8]byte,
	timeUnixNano uint64,
	observedTimeUnixNano uint64,
	severityNumber logspb.SeverityNumber,
	severityText string,
	bodyText string,
	attributes ...*commonpb.KeyValue,
) *logspb.LogRecord {
	var traceIDSlice []byte
	var spanIDSlice []byte
	if traceID != [16]byte{} {
		traceIDSlice = traceID[:]
	}
	if spanID != [8]byte{} {
		spanIDSlice = spanID[:]
	}

	return &logspb.LogRecord{
		TimeUnixNano:         timeUnixNano,
		ObservedTimeUnixNano: observedTimeUnixNano,
		SeverityNumber:       severityNumber,
		SeverityText:         severityText,
		Body: &commonpb.AnyValue{
			Value: &commonpb.AnyValue_StringValue{
				StringValue: bodyText,
			},
		},
		Attributes: attributes,
		TraceId:    traceIDSlice,
		SpanId:     spanIDSlice,
	}
}

// NewResourceLogs constructs ResourceLogs with resource attributes and scope logs.
func NewResourceLogs(
	serviceName string,
	scopeName string,
	scopeVersion string,
	records []*logspb.LogRecord,
) *logspb.ResourceLogs {
	return &logspb.ResourceLogs{
		Resource: &resourcepb.Resource{
			Attributes: []*commonpb.KeyValue{
				StringAttribute("service.name", serviceName),
			},
		},
		ScopeLogs: []*logspb.ScopeLogs{
			{
				Scope: &commonpb.InstrumentationScope{
					Name:    scopeName,
					Version: scopeVersion,
				},
				LogRecords: records,
			},
		},
	}
}

// NewLogsData wraps ResourceLogs into a LogsData container.
func NewLogsData(resLogs ...*logspb.ResourceLogs) *logspb.LogsData {
	return &logspb.LogsData{
		ResourceLogs: resLogs,
	}
}

// MarshalProto serializes LogsData to protobuf wire format.
func MarshalProto(logs *logspb.LogsData) ([]byte, error) {
	return proto.Marshal(logs)
}

// UnmarshalProto deserializes LogsData from protobuf wire format.
func UnmarshalProto(data []byte) (*logspb.LogsData, error) {
	logs := &logspb.LogsData{}
	if err := proto.Unmarshal(data, logs); err != nil {
		return nil, err
	}
	return logs, nil
}

// MarshalJSON serializes LogsData to JSON.
func MarshalJSON(logs *logspb.LogsData) ([]byte, error) {
	return protojson.Marshal(logs)
}

// UnmarshalJSON deserializes LogsData from JSON.
func UnmarshalJSON(data []byte) (*logspb.LogsData, error) {
	logs := &logspb.LogsData{}
	if err := protojson.Unmarshal(data, logs); err != nil {
		return nil, err
	}
	return logs, nil
}
spec.json
{
  "schemaVersion": 1,
  "goal": "build and serialize LogsData with ResourceLogs and LogRecord",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.opentelemetry.io/proto/otlp@v1.10.0"
  ],
  "symbols": [
    "go.opentelemetry.io/proto/otlp/logs/v1.LogsData"
  ]
}

Seeder de origen

anónimo