Created
January 11, 2023 20:34
-
-
Save ulexxander/761ba834eda9a3336a1fad31e461eaa6 to your computer and use it in GitHub Desktop.
Go test utility to dump Prometheus metrics observed during the test.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package testutil | |
| import ( | |
| "bytes" | |
| "flag" | |
| "os" | |
| "testing" | |
| "github.com/prometheus/client_golang/prometheus" | |
| "github.com/prometheus/common/expfmt" | |
| ) | |
| var flagMetrics = flag.Bool("metrics", false, "Enables dumping Prometheus metrics to stdout") | |
| func NewMetricsRegistry(t *testing.T) *prometheus.Registry { | |
| registry := prometheus.NewRegistry() | |
| t.Cleanup(func() { | |
| if !*flagMetrics { | |
| return | |
| } | |
| mfs, err := registry.Gather() | |
| if err != nil { | |
| t.Logf("Error gathering Prometheus metrics: %s", err) | |
| return | |
| } | |
| var buf bytes.Buffer | |
| encoder := expfmt.NewEncoder(&buf, expfmt.FmtText) | |
| for i, mf := range mfs { | |
| if err := encoder.Encode(mf); err != nil { | |
| t.Logf("Error encoding Prometheus metrics family %d: %s", i, err) | |
| return | |
| } | |
| } | |
| t.Log("Prometheus metrics:") | |
| os.Stdout.WriteString(buf.String()) | |
| }) | |
| return registry | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In the test code initialize metrics registry and register collectors you want to observe.
Example output: