CodeSampleX

Exemple

go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.43.0: WithoutTimestamps

Échantillon vérifié pour golang go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.43.0: WithoutTimestamps. Le contrat s'est exécuté sur go 1.26 …

sha256:cbdbd2518de0c283b38b9d2181045167b695b9c4e966b99be147b1ca88cdffd3

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
2
Clés de signature qui l’ont compilé
1
Environnement déclaré go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 FAIL compile:SKIPPED · contract:FAIL · load:SKIPPED · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-30
go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-30

Cas

HOW
Objectif
verify stdoutmetric.WithoutTimestamps in pkg:golang/go.opentelemetry.io/otel/exporters/stdout/stdoutmetric@v1.43.0
Paquets
Symboles
  • stdoutmetric.WithoutTimestamps
Environnement
go 1.26
Créé
2026-08-30T03:49:16Z

Contrat

  1. stdoutmetric.WithoutTimestamps returns a non-nil Option for exporter configuration
  2. WithoutTimestamps zeroes StartTime and Time on exported sum data points
  3. An exporter without WithoutTimestamps preserves original timestamps on exported data points
  4. WithoutTimestamps redacts timestamps when exporting metrics from MeterProvider

Fichiers

  • PROMPT.md
  • csx.json
  • exporter.go
  • go.mod
  • go.sum
  • spec.json
  • test/contract_test.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 stdoutmetric.WithoutTimestamps in pkg:golang/go.opentelemetry.io/otel/exporters/stdout/stdoutmetric@v1.43.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.opentelemetry.io/otel/exporters/stdout/stdoutmetric@v1.43.0
Demonstrate these symbols/APIs:
  - stdoutmetric.WithoutTimestamps

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:3c4f6e64a1e6353b3c8a56e77499ee5828b485165daf02e938f8f28956ab5c3b","contract":["stdoutmetric.WithoutTimestamps returns a non-nil Option for exporter configuration","WithoutTimestamps zeroes StartTime and Time on exported sum data points","An exporter without WithoutTimestamps preserves original timestamps on exported data points","WithoutTimestamps redacts timestamps when exporting metrics from MeterProvider"],"goal":"verify stdoutmetric.WithoutTimestamps in pkg:golang/go.opentelemetry.io/otel/exporters/stdout/stdoutmetric@v1.43.0","kind":"HOW","packages":["pkg:golang/go.opentelemetry.io/otel/exporters/stdout/stdoutmetric@v1.43.0"],"schemaVersion":1,"symbols":["stdoutmetric.WithoutTimestamps"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","moduleSystem":"go.mod","os":"linux","osVersionBucket":"24","packageManager":"go","runtime":"go","runtimeVersion":"1.26","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/go.opentelemetry.io/otel/exporters/stdout/stdoutmetric@v1.43.0"],"schemaVersion":1,"subject":"pkg:golang/go.opentelemetry.io/otel/exporters/stdout/stdoutmetric@v1.43.0","symbols":["stdoutmetric.WithoutTimestamps"],"verifierAdapter":"golang@1"}
exporter.go
package sample

import (
	"context"
	"fmt"
	"io"

	"go.opentelemetry.io/otel/exporters/stdout/stdoutmetric"
	"go.opentelemetry.io/otel/sdk/metric"
	"go.opentelemetry.io/otel/sdk/metric/metricdata"
)

// MetricExporterConfig encapsulates options for creating a stdoutmetric exporter.
type MetricExporterConfig struct {
	WithoutTimestamps bool
	PrettyPrint       bool
	Writer            io.Writer
}

// NewExporter creates a stdoutmetric exporter configured with options.
func NewExporter(cfg MetricExporterConfig) (metric.Exporter, error) {
	var opts []stdoutmetric.Option

	if cfg.WithoutTimestamps {
		opts = append(opts, stdoutmetric.WithoutTimestamps())
	}
	if cfg.PrettyPrint {
		opts = append(opts, stdoutmetric.WithPrettyPrint())
	}
	if cfg.Writer != nil {
		opts = append(opts, stdoutmetric.WithWriter(cfg.Writer))
	}

	exp, err := stdoutmetric.New(opts...)
	if err != nil {
		return nil, fmt.Errorf("failed to create stdoutmetric exporter: %w", err)
	}
	return exp, nil
}

// NewMeterProvider creates a MeterProvider configured with a stdoutmetric exporter.
func NewMeterProvider(w io.Writer, withoutTimestamps bool) (*metric.MeterProvider, error) {
	exp, err := NewExporter(MetricExporterConfig{
		WithoutTimestamps: withoutTimestamps,
		PrettyPrint:       false,
		Writer:            w,
	})
	if err != nil {
		return nil, err
	}

	reader := metric.NewPeriodicReader(exp)
	mp := metric.NewMeterProvider(metric.WithReader(reader))
	return mp, nil
}

// ExportResourceMetrics exports resource metrics directly through the metric exporter.
func ExportResourceMetrics(ctx context.Context, exp metric.Exporter, rm *metricdata.ResourceMetrics) error {
	if exp == nil {
		return fmt.Errorf("exporter cannot be nil")
	}
	return exp.Export(ctx, rm)
}
go.mod
module example.com/otel-stdoutmetric-without-timestamps

go 1.25.0

require (
	go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.43.0
	go.opentelemetry.io/otel/sdk v1.43.0
	go.opentelemetry.io/otel/sdk/metric v1.43.0
)

require (
	github.com/cespare/xxhash/v2 v2.3.0 // indirect
	github.com/go-logr/logr v1.4.4 // indirect
	github.com/go-logr/stdr v1.2.2 // indirect
	github.com/google/uuid v1.6.0 // indirect
	go.opentelemetry.io/auto/sdk v1.2.1 // indirect
	go.opentelemetry.io/otel v1.43.0 // indirect
	go.opentelemetry.io/otel/metric v1.43.0 // indirect
	go.opentelemetry.io/otel/trace v1.43.0 // indirect
	golang.org/x/sys v0.47.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/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/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
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/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
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/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=
go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.43.0 h1:TC+BewnDpeiAmcscXbGMfxkO+mwYUwE/VySwvw88PfA=
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.43.0/go.mod h1:J/ZyF4vfPwsSr9xJSPyQ4LqtcTPULFR64KwTikGLe+A=
go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=
go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=
go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=
go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg=
go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw=
go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=
go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify stdoutmetric.WithoutTimestamps in pkg:golang/go.opentelemetry.io/otel/exporters/stdout/stdoutmetric@v1.43.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.opentelemetry.io/otel/exporters/stdout/stdoutmetric@v1.43.0"
  ],
  "symbols": [
    "stdoutmetric.WithoutTimestamps"
  ]
}
test/contract_test.go
package test

import (
	"bytes"
	"context"
	"strings"
	"testing"
	"time"

	sample "example.com/otel-stdoutmetric-without-timestamps"
	"go.opentelemetry.io/otel/exporters/stdout/stdoutmetric"
	"go.opentelemetry.io/otel/sdk/instrumentation"
	"go.opentelemetry.io/otel/sdk/metric/metricdata"
)

func newSampleResourceMetrics() *metricdata.ResourceMetrics {
	startTime := time.Date(2026, 8, 30, 10, 0, 0, 0, time.UTC)
	endTime := time.Date(2026, 8, 30, 10, 5, 0, 0, time.UTC)
	return &metricdata.ResourceMetrics{
		ScopeMetrics: []metricdata.ScopeMetrics{
			{
				Scope: instrumentation.Scope{
					Name:    "example.com/test-scope",
					Version: "1.0.0",
				},
				Metrics: []metricdata.Metrics{
					{
						Name:        "http_requests_total",
						Description: "Total HTTP requests",
						Unit:        "1",
						Data: metricdata.Sum[int64]{
							Temporality: metricdata.CumulativeTemporality,
							IsMonotonic: true,
							DataPoints: []metricdata.DataPoint[int64]{
								{
									StartTime: startTime,
									Time:      endTime,
									Value:     42,
								},
							},
						},
					},
					{
						Name:        "latency_seconds",
						Description: "Request latency",
						Unit:        "s",
						Data: metricdata.Histogram[float64]{
							Temporality: metricdata.CumulativeTemporality,
							DataPoints: []metricdata.HistogramDataPoint[float64]{
								{
									StartTime:    startTime,
									Time:         endTime,
									Count:        1,
									Sum:          0.125,
									Bounds:       []float64{0.1, 0.5, 1.0},
									BucketCounts: []uint64{0, 1, 0, 0},
								},
							},
						},
					},
				},
			},
		},
	}
}

func TestWithoutTimestampsContract(t *testing.T) {
	ctx := context.Background()

	// 1. stdoutmetric.WithoutTimestamps returns a non-nil Option for exporter configuration
	opt := stdoutmetric.WithoutTimestamps()
	if opt == nil {
		t.Fatal("expected stdoutmetric.WithoutTimestamps() to return non-nil Option")
	}

	// 2. WithoutTimestamps zeroes StartTime and Time on exported sum data points
	var bufWithout bytes.Buffer
	expWithout, err := sample.NewExporter(sample.MetricExporterConfig{
		WithoutTimestamps: true,
		Writer:            &bufWithout,
	})
	if err != nil {
		t.Fatalf("failed to create exporter with WithoutTimestamps: %v", err)
	}

	rmWithout := newSampleResourceMetrics()
	if err := sample.ExportResourceMetrics(ctx, expWithout, rmWithout); err != nil {
		t.Fatalf("failed to export resource metrics without timestamps: %v", err)
	}

	outWithout := bufWithout.String()
	if !strings.Contains(outWithout, `"StartTime":"0001-01-01T00:00:00Z"`) {
		t.Fatalf("expected StartTime to be zero time, got: %s", outWithout)
	}
	if !strings.Contains(outWithout, `"Time":"0001-01-01T00:00:00Z"`) {
		t.Fatalf("expected Time to be zero time, got: %s", outWithout)
	}
	if strings.Contains(outWithout, "2026-08-30") {
		t.Fatalf("expected no timestamp occurrences of 2026-08-30, got: %s", outWithout)
	}

	// 3. An exporter without WithoutTimestamps preserves original timestamps on exported data points
	var bufWith bytes.Buffer
	expWith, err := sample.NewExporter(sample.MetricExporterConfig{
		WithoutTimestamps: false,
		Writer:            &bufWith,
	})
	if err != nil {
		t.Fatalf("failed to create exporter with timestamps: %v", err)
	}

	rmWith := newSampleResourceMetrics()
	if err := sample.ExportResourceMetrics(ctx, expWith, rmWith); err != nil {
		t.Fatalf("failed to export resource metrics with timestamps: %v", err)
	}

	outWith := bufWith.String()
	if !strings.Contains(outWith, "2026-08-30T10:00:00Z") {
		t.Fatalf("expected StartTime to contain original timestamp, got: %s", outWith)
	}
	if !strings.Contains(outWith, "2026-08-30T10:05:00Z") {
		t.Fatalf("expected Time to contain original timestamp, got: %s", outWith)
	}

	// 4. WithoutTimestamps redacts timestamps when exporting metrics from MeterProvider
	var bufMP bytes.Buffer
	mp, err := sample.NewMeterProvider(&bufMP, true)
	if err != nil {
		t.Fatalf("failed to create MeterProvider: %v", err)
	}

	meter := mp.Meter("example.com/test-meter")
	counter, err := meter.Int64Counter("items_processed")
	if err != nil {
		t.Fatalf("failed to create counter: %v", err)
	}

	counter.Add(ctx, 10)

	if err := mp.ForceFlush(ctx); err != nil {
		t.Fatalf("failed to force flush meter provider: %v", err)
	}
	if err := mp.Shutdown(ctx); err != nil {
		t.Fatalf("failed to shutdown meter provider: %v", err)
	}

	mpOutput := bufMP.String()
	if !strings.Contains(mpOutput, `"items_processed"`) {
		t.Fatalf("expected meter provider output to contain items_processed, got: %s", mpOutput)
	}
	if !strings.Contains(mpOutput, `"StartTime":"0001-01-01T00:00:00Z"`) {
		t.Fatalf("expected StartTime in MeterProvider output to be zero time, got: %s", mpOutput)
	}
	if !strings.Contains(mpOutput, `"Time":"0001-01-01T00:00:00Z"`) {
		t.Fatalf("expected Time in MeterProvider output to be zero time, got: %s", mpOutput)
	}
}

Seeder d'origine

anonyme