Skip to content

Instantly share code, notes, and snippets.

@ulexxander
Created January 11, 2023 20:34
Show Gist options
  • Select an option

  • Save ulexxander/761ba834eda9a3336a1fad31e461eaa6 to your computer and use it in GitHub Desktop.

Select an option

Save ulexxander/761ba834eda9a3336a1fad31e461eaa6 to your computer and use it in GitHub Desktop.
Go test utility to dump Prometheus metrics observed during the test.
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
}
@ulexxander

Copy link
Copy Markdown
Author

In the test code initialize metrics registry and register collectors you want to observe.

Example output:

$ go test -v -metrics
=== RUN   TestHandler
    metrics.go:39: Prometheus metrics:
# HELP wsnotifier_websocket_connection_duration_seconds 
# TYPE wsnotifier_websocket_connection_duration_seconds summary
wsnotifier_websocket_connection_duration_seconds_sum 9.6651e-05
wsnotifier_websocket_connection_duration_seconds_count 1
# HELP wsnotifier_websocket_handshake_duration 
# TYPE wsnotifier_websocket_handshake_duration summary
wsnotifier_websocket_handshake_duration_sum 9.5392e-05
wsnotifier_websocket_handshake_duration_count 1
# HELP wsnotifier_websocket_open_connection 
# TYPE wsnotifier_websocket_open_connection gauge
wsnotifier_websocket_open_connection 0
--- PASS: TestHandler (0.00s)
PASS
ok      gitlab.com/adc-sistemi/backend/websocket-notifier/ws    0.004s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment