CodeSampleX

サンプル

go.opentelemetry.io/otel/exporters/prometheus v0.65.0: WithResourceAsConstantLabels

検証済みサンプル — golang go.opentelemetry.io/otel/exporters/prometheus v0.65.0: WithResourceAsConstantLabels. go 1.26 · linux debian/x64 · docker で contract…

sha256:23706746f2012e4ed912377f222282ee9390ea63e4dbbb96f40d98b182fee025

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

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
3
ビルドした署名鍵
1
宣言された環境 linux 24 · ubuntu · glibc 2.39 x64 go

検証実行環境

環境 コントラクト ステージ 実行日
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 FAIL compile:SKIPPED · contract:FAIL · load:SKIPPED · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-07
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 FAIL compile:SKIPPED · contract:FAIL · load:SKIPPED · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-07
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-08

ケース

HOW
ゴール
verify prometheus.WithResourceAsConstantLabels in pkg:golang/go.opentelemetry.io/otel/exporters/prometheus@v0.65.0
パッケージ
シンボル
  • prometheus.WithResourceAsConstantLabels
作成日
2026-09-07T06:40:51Z

コントラクト

  1. WithResourceAsConstantLabels returns an Option that configures exporter options
  2. Resource attributes matching the filter are attached as constant labels on exported Prometheus metric families
  3. Resource attributes excluded by the filter are not attached as constant labels on exported metric families
  4. Prometheus exporter with WithResourceAsConstantLabels correctly collects recorded metric observations

ファイル

  • PROMPT.md
  • csx.json
  • exporter.go
  • go.mod
  • go.sum
  • 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 prometheus.WithResourceAsConstantLabels in pkg:golang/go.opentelemetry.io/otel/exporters/prometheus@v0.65.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.opentelemetry.io/otel/exporters/prometheus@v0.65.0
Demonstrate these symbols/APIs:
  - prometheus.WithResourceAsConstantLabels

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:651cb408b7dc219ada49a5f5c671e886fe7d28f2e375fd97c364e37847c2e51e","contract":["WithResourceAsConstantLabels returns an Option that configures exporter options","Resource attributes matching the filter are attached as constant labels on exported Prometheus metric families","Resource attributes excluded by the filter are not attached as constant labels on exported metric families","Prometheus exporter with WithResourceAsConstantLabels correctly collects recorded metric observations"],"goal":"verify prometheus.WithResourceAsConstantLabels in pkg:golang/go.opentelemetry.io/otel/exporters/prometheus@v0.65.0","kind":"HOW","packages":["pkg:golang/go.opentelemetry.io/otel/exporters/prometheus@v0.65.0"],"schemaVersion":1,"symbols":["prometheus.WithResourceAsConstantLabels"]},"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/exporters/prometheus@v0.65.0"],"schemaVersion":1,"subject":"pkg:golang/go.opentelemetry.io/otel/exporters/prometheus@v0.65.0","symbols":["prometheus.WithResourceAsConstantLabels"],"verifierAdapter":"golang@1"}
exporter.go
package sample

import (
	"context"
	"fmt"

	promclient "github.com/prometheus/client_golang/prometheus"
	"go.opentelemetry.io/otel/attribute"
	otelprom "go.opentelemetry.io/otel/exporters/prometheus"
	"go.opentelemetry.io/otel/metric"
	sdkmetric "go.opentelemetry.io/otel/sdk/metric"
	"go.opentelemetry.io/otel/sdk/resource"
)

// SetupPrometheusExporter initializes a Prometheus exporter with resource attributes
// converted to constant labels based on the provided filter.
func SetupPrometheusExporter(res *resource.Resource, filter attribute.Filter, reg promclient.Registerer) (*sdkmetric.MeterProvider, *otelprom.Exporter, error) {
	opts := []otelprom.Option{
		otelprom.WithResourceAsConstantLabels(filter),
	}
	if reg != nil {
		opts = append(opts, otelprom.WithRegisterer(reg))
	}

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

	mpOpts := []sdkmetric.Option{
		sdkmetric.WithReader(exporter),
	}
	if res != nil {
		mpOpts = append(mpOpts, sdkmetric.WithResource(res))
	}

	mp := sdkmetric.NewMeterProvider(mpOpts...)
	return mp, exporter, nil
}

// RecordSampleMetric records a count on a counter instrument.
func RecordSampleMetric(ctx context.Context, mp metric.MeterProvider, meterName, counterName string, count int64, attrs ...attribute.KeyValue) error {
	meter := mp.Meter(meterName)
	counter, err := meter.Int64Counter(counterName)
	if err != nil {
		return fmt.Errorf("failed to create counter: %w", err)
	}
	counter.Add(ctx, count, metric.WithAttributes(attrs...))
	return nil
}
go.mod
module example.com/otel-prometheus-resource-labels

go 1.26.6

require (
	github.com/prometheus/client_golang v1.23.2
	go.opentelemetry.io/otel v1.43.0
	go.opentelemetry.io/otel/exporters/prometheus v0.65.0
	go.opentelemetry.io/otel/metric v1.43.0
	go.opentelemetry.io/otel/sdk v1.43.0
	go.opentelemetry.io/otel/sdk/metric v1.43.0
)

require (
	github.com/beorn7/perks v1.0.1 // indirect
	github.com/cespare/xxhash/v2 v2.3.0 // indirect
	github.com/go-logr/logr v1.4.3 // indirect
	github.com/go-logr/stdr v1.2.2 // indirect
	github.com/google/uuid v1.6.0 // indirect
	github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
	github.com/prometheus/client_model v0.6.2 // indirect
	github.com/prometheus/common v0.67.5 // indirect
	github.com/prometheus/otlptranslator v1.0.0 // indirect
	github.com/prometheus/procfs v0.20.1 // indirect
	go.opentelemetry.io/auto/sdk v1.2.1 // indirect
	go.opentelemetry.io/otel/trace v1.43.0 // indirect
	go.yaml.in/yaml/v2 v2.4.4 // indirect
	golang.org/x/sys v0.42.0 // indirect
	google.golang.org/protobuf v1.36.11 // indirect
)
go.sum
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
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.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/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/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
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/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4=
github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw=
github.com/prometheus/otlptranslator v1.0.0 h1:s0LJW/iN9dkIH+EnhiD3BlkkP5QVIUVEoIwkU+A6qos=
github.com/prometheus/otlptranslator v1.0.0/go.mod h1:vRYWnXvI6aWGpsdY/mOT/cbeVRBlPWtBNDb7kGR3uKM=
github.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc=
github.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo=
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/prometheus v0.65.0 h1:jOveH/b4lU9HT7y+Gfamf18BqlOuz2PWEvs8yM7Q6XE=
go.opentelemetry.io/otel/exporters/prometheus v0.65.0/go.mod h1:i1P8pcumauPtUI4YNopea1dhzEMuEqWP1xoUZDylLHo=
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=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
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 prometheus.WithResourceAsConstantLabels in pkg:golang/go.opentelemetry.io/otel/exporters/prometheus@v0.65.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.opentelemetry.io/otel/exporters/prometheus@v0.65.0"
  ],
  "symbols": [
    "prometheus.WithResourceAsConstantLabels"
  ]
}
test/contract_test.go
package test

import (
	"context"
	"testing"

	promclient "github.com/prometheus/client_golang/prometheus"
	"go.opentelemetry.io/otel/attribute"
	otelprom "go.opentelemetry.io/otel/exporters/prometheus"
	"go.opentelemetry.io/otel/sdk/resource"

	sample "example.com/otel-prometheus-resource-labels"
)

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

	// 1. WithResourceAsConstantLabels returns a non-nil Option
	filter := attribute.NewAllowKeysFilter("service.environment", "region")
	opt := otelprom.WithResourceAsConstantLabels(filter)
	if opt == nil {
		t.Fatal("expected WithResourceAsConstantLabels to return non-nil Option")
	}

	// 2. Resource attributes matching the filter are attached as constant labels on exported metrics
	res, err := resource.New(ctx,
		resource.WithAttributes(
			attribute.String("service.environment", "production"),
			attribute.String("region", "us-central"),
			attribute.String("host.name", "worker-01"),
		),
	)
	if err != nil {
		t.Fatalf("failed to create resource: %v", err)
	}

	reg := promclient.NewRegistry()
	mp, exporter, err := sample.SetupPrometheusExporter(res, filter, reg)
	if err != nil {
		t.Fatalf("failed to setup prometheus exporter: %v", err)
	}
	defer func() {
		_ = mp.Shutdown(ctx)
	}()

	if exporter == nil {
		t.Fatal("expected exporter to be non-nil")
	}

	// Record an observation
	err = sample.RecordSampleMetric(ctx, mp, "example.com/meter", "http_requests_total", 42, attribute.String("status_code", "200"))
	if err != nil {
		t.Fatalf("failed to record metric: %v", err)
	}

	// Gather metrics from Prometheus registry
	metricFamilies, err := reg.Gather()
	if err != nil {
		t.Fatalf("failed to gather metrics from registry: %v", err)
	}

	var foundCounter bool
	for _, mf := range metricFamilies {
		if mf.GetName() == "http_requests_total" {
			foundCounter = true
			if len(mf.GetMetric()) == 0 {
				t.Fatal("expected at least one metric point in http_requests_total")
			}
			m := mf.GetMetric()[0]
			labels := make(map[string]string)
			for _, lp := range m.GetLabel() {
				labels[lp.GetName()] = lp.GetValue()
			}

			// Verify custom metric attribute
			if got := labels["status_code"]; got != "200" {
				t.Errorf("expected status_code label to be '200', got %q", got)
			}

			// Verify allowed resource constant labels (sanitized dots to underscores)
			if got := labels["service_environment"]; got != "production" {
				t.Errorf("expected service_environment label to be 'production', got %q", got)
			}
			if got := labels["region"]; got != "us-central" {
				t.Errorf("expected region label to be 'us-central', got %q", got)
			}

			// 3. Resource attributes excluded by the filter are not attached as constant labels
			if _, exists := labels["host_name"]; exists {
				t.Errorf("expected host_name to be excluded by filter, but found in labels: %v", labels)
			}

			// Verify metric value
			if m.GetCounter() == nil || m.GetCounter().GetValue() != 42 {
				t.Errorf("expected counter value 42, got %v", m.GetCounter())
			}
		}
	}

	if !foundCounter {
		t.Fatal("metric http_requests_total was not found in gathered metric families")
	}
}

オリジンシーダー

匿名