diff --git a/prometheus/push/push.go b/prometheus/push/push.go index a0d009c21..0647f6829 100644 --- a/prometheus/push/push.go +++ b/prometheus/push/push.go @@ -168,6 +168,16 @@ func (p *Pusher) Collector(c prometheus.Collector) *Pusher { return p } +// MustCollector works like Collector but registers any number of +// Collectors and panics upon the first registration that causes an +// error. +// +// For convenience, this method returns a pointer to the Pusher itself. +func (p *Pusher) MustCollector(c ...prometheus.Collector) *Pusher { + p.registerer.MustRegister(c...) + return p +} + // Grouping adds a label pair to the grouping key of the Pusher, replacing any // previously added label pair with the same label name. Note that setting any // labels in the grouping key that are already contained in the metrics to push diff --git a/prometheus/push/push_test.go b/prometheus/push/push_test.go index 3367a4b56..a5f0014e9 100644 --- a/prometheus/push/push_test.go +++ b/prometheus/push/push_test.go @@ -107,6 +107,22 @@ func TestPush(t *testing.T) { t.Error("unexpected path:", lastPath) } + // use MustCollectors, all good. + if err := New(pgwOK.URL, "testjob"). + MustCollector(metric1, metric2). + Push(); err != nil { + t.Fatal(err) + } + if lastMethod != http.MethodPut { + t.Errorf("got method %q for Push, want %q", lastMethod, http.MethodPut) + } + if !bytes.Equal(lastBody, wantBody) { + t.Errorf("got body %v, want %v", lastBody, wantBody) + } + if lastPath != "/metrics/job/testjob" { + t.Error("unexpected path:", lastPath) + } + // Add some Collectors, with nil grouping, all good. if err := New(pgwOK.URL, "testjob"). Collector(metric1).