샘플
github.com/prometheus/common v0.48.0: Parse Prometheus text exposition format metrics into metric families using expfmt.TextParser
검증된 샘플 — golang github.com/prometheus/common v0.48.0: Parse Prometheus text exposition format metrics into metric families using expfmt.TextParser. go 1.26 …
sha256:11620403c1eb9826ec622c9bde16e3b997e0be7caf94a945ce54a87e42a7cdb7
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 1
- 빌드한 서명 키
- 1
선언된 환경
go linux x64 go go go
검증 실행 환경
| 환경 | 컨트랙트 | 단계 | 실행일 |
|---|---|---|---|
| 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-23 |
케이스
HOW- 목표
- Parse Prometheus text exposition format metrics into metric families using expfmt.TextParser
- 심벌
-
- github.com/prometheus/common/expfmt.TextParser.TextToMetricFamilies
- 환경
- go
- 생성일
- 2026-08-23T17:04:07Z
컨트랙트
- TextParser.TextToMetricFamilies parses Prometheus text format exposition input into a map of MetricFamily pointers keyed by metric family name.
- HELP and TYPE comments are correctly parsed into MetricFamily Help and Type metadata (such as MetricType_COUNTER and MetricType_GAUGE).
- Parsed metrics contain label name and value pairs as well as numeric counter or gauge sample values and optional millisecond timestamps.
- Exposition input streams with multiple distinct metric families are parsed into separate map entries.
- Malformed metric exposition input produces a non-nil parse error.
파일
- NOTES.md
- PROMPT.md
- csx.json
- go.mod
- go.sum
- parser_test.go
- spec.json
소스
# github.com/prometheus/common/expfmt Exposition Parser
## Prior Knowledge Search
A query to search known solutions for `pkg:golang/github.com/prometheus/common@v0.48.0` returned `NO_SAFE_MATCH`. This sample establishes verified coverage for parsing Prometheus text exposition formats into metric families.
## Pinned Release
- `github.com/prometheus/common`: `v0.48.0`
- `github.com/prometheus/client_model`: `v0.5.0`
- `google.golang.org/protobuf`: `v1.32.0`
## Proven Behaviors and Semantics
### 1. Parsing Counter and Gauge Metrics into MetricFamily Maps
`expfmt.TextParser.TextToMetricFamilies` reads an `io.Reader` of Prometheus exposition text and produces a map of `*dto.MetricFamily` keyed by the metric family name.
- HELP and TYPE metadata lines are parsed into `MetricFamily.Help` and `MetricFamily.Type`.
- Individual sample lines are parsed into elements of `MetricFamily.Metric`, with labels parsed into `[]*dto.LabelPair`.
- Numeric values and timestamps (when provided) are correctly populated in the metric's typed payload (`Counter.Value`, `Gauge.Value`, `TimestampMs`).
### 2. Multi-Metric and Multi-Family Parsing
A single exposition input stream containing multiple distinct metric families (e.g., counters and gauges) is parsed into separate map entries corresponding to each family name.
### 3. Syntax Error Detection
Malformed metric input (such as unquoted label values or invalid syntax) produces a non-nil parse error rather than silent corruption or panic.
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: Parse Prometheus text exposition format metrics into metric families using expfmt.TextParser
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:golang/github.com/prometheus/common@v0.48.0
Demonstrate these symbols/APIs:
- github.com/prometheus/common/expfmt.TextParser.TextToMetricFamilies
Constraints:
- executionContext: node
Required runtime conditions:
- ecosystem: npm
- language: javascript
- moduleSystem: cjs
- packageManager: npm@10.9.8
- runtime: node@22.23.2
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.
{"case":{"caseId":"case:sha256:dd1a55602fd64c50df04d68fb85d817563f74d1e6e2de81025648038ec906d25","contract":["TextParser.TextToMetricFamilies parses Prometheus text format exposition input into a map of MetricFamily pointers keyed by metric family name.","HELP and TYPE comments are correctly parsed into MetricFamily Help and Type metadata (such as MetricType_COUNTER and MetricType_GAUGE).","Parsed metrics contain label name and value pairs as well as numeric counter or gauge sample values and optional millisecond timestamps.","Exposition input streams with multiple distinct metric families are parsed into separate map entries.","Malformed metric exposition input produces a non-nil parse error."],"goal":"Parse Prometheus text exposition format metrics into metric families using expfmt.TextParser","kind":"HOW","packages":["pkg:golang/github.com/prometheus/common@v0.48.0"],"schemaVersion":1,"symbols":["github.com/prometheus/common/expfmt.TextParser.TextToMetricFamilies"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/prometheus/common@v0.48.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/prometheus/common@v0.48.0","symbols":["github.com/prometheus/common/expfmt.TextParser.TextToMetricFamilies"],"verifierAdapter":"golang@1"}
module example.com/csx-prometheus-common-test
go 1.26.5
require (
github.com/prometheus/client_model v0.5.0
github.com/prometheus/common v0.48.0
)
require google.golang.org/protobuf v1.32.0 // indirect
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/prometheus/client_model v0.5.0 h1:VQw1hfvPvk3Uv6Qf29VrPF32JB6rtbgI6cYPYQjL0Qw=
github.com/prometheus/client_model v0.5.0/go.mod h1:dTiFglRmd66nLR9Pv9f0mZi7B7fk5Pm3gvsjB5tr+kI=
github.com/prometheus/common v0.48.0 h1:QO8U2CdOzSn1BBsmXJXduaaW+dY/5QLjfB8svtSzKKE=
github.com/prometheus/common v0.48.0/go.mod h1:0/KsvlIEfPQCQ5I2iNSAWKPZziNCvRs5EC6ILDTlAPc=
google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I=
google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
package main
import (
"strings"
"testing"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/expfmt"
)
func TestTextToMetricFamiliesCounter(t *testing.T) {
input := `# HELP http_requests_total The total number of HTTP requests.
# TYPE http_requests_total counter
http_requests_total{method="post",code="200"} 1027 1395066363000
http_requests_total{method="post",code="400"} 3 1395066363000
`
var parser expfmt.TextParser
metricFamilies, err := parser.TextToMetricFamilies(strings.NewReader(input))
if err != nil {
t.Fatalf("unexpected error parsing counter metrics: %v", err)
}
mf, exists := metricFamilies["http_requests_total"]
if !exists {
t.Fatalf("expected metric family 'http_requests_total' not found")
}
if mf.GetName() != "http_requests_total" {
t.Errorf("expected name 'http_requests_total', got %q", mf.GetName())
}
if mf.GetHelp() != "The total number of HTTP requests." {
t.Errorf("expected help text 'The total number of HTTP requests.', got %q", mf.GetHelp())
}
if mf.GetType() != dto.MetricType_COUNTER {
t.Errorf("expected metric type COUNTER, got %v", mf.GetType())
}
metrics := mf.GetMetric()
if len(metrics) != 2 {
t.Fatalf("expected 2 metrics in family, got %d", len(metrics))
}
// Verify first metric
m0 := metrics[0]
if m0.GetCounter().GetValue() != 1027 {
t.Errorf("expected counter value 1027, got %v", m0.GetCounter().GetValue())
}
if m0.GetTimestampMs() != 1395066363000 {
t.Errorf("expected timestamp 1395066363000, got %v", m0.GetTimestampMs())
}
labels := m0.GetLabel()
if len(labels) != 2 {
t.Fatalf("expected 2 labels on metric 0, got %d", len(labels))
}
labelMap := make(map[string]string)
for _, l := range labels {
labelMap[l.GetName()] = l.GetValue()
}
if labelMap["method"] != "post" || labelMap["code"] != "200" {
t.Errorf("unexpected label map: %v", labelMap)
}
}
func TestTextToMetricFamiliesGauge(t *testing.T) {
input := `# HELP node_memory_bytes Node memory usage in bytes.
# TYPE node_memory_bytes gauge
node_memory_bytes{type="free"} 1048576.5
node_memory_bytes{type="used"} 2097152
`
var parser expfmt.TextParser
metricFamilies, err := parser.TextToMetricFamilies(strings.NewReader(input))
if err != nil {
t.Fatalf("unexpected error parsing gauge metrics: %v", err)
}
mf, exists := metricFamilies["node_memory_bytes"]
if !exists {
t.Fatalf("expected metric family 'node_memory_bytes' not found")
}
if mf.GetType() != dto.MetricType_GAUGE {
t.Errorf("expected metric type GAUGE, got %v", mf.GetType())
}
metrics := mf.GetMetric()
if len(metrics) != 2 {
t.Fatalf("expected 2 metrics, got %d", len(metrics))
}
if metrics[0].GetGauge().GetValue() != 1048576.5 {
t.Errorf("expected gauge value 1048576.5, got %v", metrics[0].GetGauge().GetValue())
}
if metrics[1].GetGauge().GetValue() != 2097152 {
t.Errorf("expected gauge value 2097152, got %v", metrics[1].GetGauge().GetValue())
}
}
func TestTextToMetricFamiliesMultipleFamilies(t *testing.T) {
input := `# HELP rpc_duration_seconds A summary of the RPC duration in seconds.
# TYPE rpc_duration_seconds gauge
rpc_duration_seconds{service="auth"} 0.012
# HELP app_version_info Application version info.
# TYPE app_version_info counter
app_version_info{version="1.0.0"} 1
`
var parser expfmt.TextParser
metricFamilies, err := parser.TextToMetricFamilies(strings.NewReader(input))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(metricFamilies) != 2 {
t.Fatalf("expected 2 metric families, got %d", len(metricFamilies))
}
if _, ok := metricFamilies["rpc_duration_seconds"]; !ok {
t.Errorf("expected family 'rpc_duration_seconds' missing")
}
if _, ok := metricFamilies["app_version_info"]; !ok {
t.Errorf("expected family 'app_version_info' missing")
}
}
func TestTextToMetricFamiliesSyntaxError(t *testing.T) {
invalidInput := `http_requests_total{method="post",code=200} 1027
`
var parser expfmt.TextParser
_, err := parser.TextToMetricFamilies(strings.NewReader(invalidInput))
if err == nil {
t.Fatalf("expected parse error for unquoted label value, got nil")
}
}
{
"schemaVersion": 1,
"goal": "Parse Prometheus text exposition format metrics into metric families using expfmt.TextParser",
"kind": "HOW",
"packages": [
"pkg:golang/github.com/prometheus/common@v0.48.0"
],
"symbols": [
"github.com/prometheus/common/expfmt.TextParser.TextToMetricFamilies"
],
"constraints": {
"executionContext": "node"
},
"runtimeConditions": {
"ecosystem": "npm",
"language": "javascript",
"moduleSystem": "cjs",
"packageManager": "npm@10.9.8",
"runtime": "node@22.23.2"
}
}
오리진 시더
익명