MCPcopy
hub / github.com/prometheus/client_golang / ExampleCounterVec

Function ExampleCounterVec

prometheus/examples_test.go:132–174  ·  prometheus/examples_test.go::ExampleCounterVec
()

Source from the content-addressed store, hash-verified

130}
131
132func ExampleCounterVec() {
133 httpReqs := prometheus.NewCounterVec(
134 prometheus.CounterOpts{
135 Name: "http_requests_total",
136 Help: "How many HTTP requests processed, partitioned by status code and HTTP method.",
137 },
138 []string{"code", "method"},
139 )
140 prometheus.MustRegister(httpReqs)
141
142 httpReqs.WithLabelValues("404", "POST").Add(42)
143
144 // If you have to access the same set of labels very frequently, it
145 // might be good to retrieve the metric only once and keep a handle to
146 // it. But beware of deletion of that metric, see below!
147 m := httpReqs.WithLabelValues("200", "GET")
148 for i := 0; i < 1000000; i++ {
149 m.Inc()
150 }
151 // Delete a metric from the vector. If you have previously kept a handle
152 // to that metric (as above), future updates via that handle will go
153 // unseen (even if you re-create a metric with the same label set
154 // later).
155 httpReqs.DeleteLabelValues("200", "GET")
156 // Same thing with the more verbose Labels syntax.
157 httpReqs.Delete(prometheus.Labels{"method": "GET", "code": "200"})
158
159 // Just for demonstration, let's check the state of the counter vector
160 // by registering it with a custom registry and then let it collect the
161 // metrics.
162 reg := prometheus.NewRegistry()
163 reg.MustRegister(httpReqs)
164
165 metricFamilies, err := reg.Gather()
166 if err != nil || len(metricFamilies) != 1 {
167 panic("unexpected behavior of custom test registry")
168 }
169
170 fmt.Println(toNormalizedJSON(sanitizeMetricFamily(metricFamilies[0])))
171
172 // Output:
173 // {"name":"http_requests_total","help":"How many HTTP requests processed, partitioned by status code and HTTP method.","type":"COUNTER","metric":[{"label":[{"name":"code","value":"404"},{"name":"method","value":"POST"}],"counter":{"value":42,"createdTimestamp":"1970-01-01T00:00:10Z"}}]}
174}
175
176func ExampleRegister() {
177 // Imagine you have a worker pool and want to count the tasks completed.

Callers

nothing calls this directly

Calls 13

WithLabelValuesMethod · 0.95
MustRegisterMethod · 0.95
GatherMethod · 0.95
NewCounterVecFunction · 0.92
MustRegisterFunction · 0.92
NewRegistryFunction · 0.92
toNormalizedJSONFunction · 0.85
sanitizeMetricFamilyFunction · 0.85
DeleteLabelValuesMethod · 0.80
AddMethod · 0.65
IncMethod · 0.65
PrintlnMethod · 0.65

Tested by

no test coverage detected