()
| 174 | } |
| 175 | |
| 176 | func ExampleRegister() { |
| 177 | // Imagine you have a worker pool and want to count the tasks completed. |
| 178 | taskCounter := prometheus.NewCounter(prometheus.CounterOpts{ |
| 179 | Subsystem: "worker_pool", |
| 180 | Name: "completed_tasks_total", |
| 181 | Help: "Total number of tasks completed.", |
| 182 | }) |
| 183 | // This will register fine. |
| 184 | if err := prometheus.Register(taskCounter); err != nil { |
| 185 | fmt.Println(err) |
| 186 | } else { |
| 187 | fmt.Println("taskCounter registered.") |
| 188 | } |
| 189 | // Don't forget to tell the HTTP server about the Prometheus handler. |
| 190 | // (In a real program, you still need to start the HTTP server...) |
| 191 | http.Handle("/metrics", promhttp.Handler()) |
| 192 | |
| 193 | // Now you can start workers and give every one of them a pointer to |
| 194 | // taskCounter and let it increment it whenever it completes a task. |
| 195 | taskCounter.Inc() // This has to happen somewhere in the worker code. |
| 196 | |
| 197 | // But wait, you want to see how individual workers perform. So you need |
| 198 | // a vector of counters, with one element for each worker. |
| 199 | taskCounterVec := prometheus.NewCounterVec( |
| 200 | prometheus.CounterOpts{ |
| 201 | Subsystem: "worker_pool", |
| 202 | Name: "completed_tasks_total", |
| 203 | Help: "Total number of tasks completed.", |
| 204 | }, |
| 205 | []string{"worker_id"}, |
| 206 | ) |
| 207 | |
| 208 | // Registering will fail because we already have a metric of that name. |
| 209 | if err := prometheus.Register(taskCounterVec); err != nil { |
| 210 | fmt.Println("taskCounterVec not registered:", err) |
| 211 | } else { |
| 212 | fmt.Println("taskCounterVec registered.") |
| 213 | } |
| 214 | |
| 215 | // To fix, first unregister the old taskCounter. |
| 216 | if prometheus.Unregister(taskCounter) { |
| 217 | fmt.Println("taskCounter unregistered.") |
| 218 | } |
| 219 | |
| 220 | // Try registering taskCounterVec again. |
| 221 | if err := prometheus.Register(taskCounterVec); err != nil { |
| 222 | fmt.Println("taskCounterVec not registered:", err) |
| 223 | } else { |
| 224 | fmt.Println("taskCounterVec registered.") |
| 225 | } |
| 226 | // Bummer! Still doesn't work. |
| 227 | |
| 228 | // Prometheus will not allow you to ever export metrics with |
| 229 | // inconsistent help strings or label names. After unregistering, the |
| 230 | // unregistered metrics will cease to show up in the /metrics HTTP |
| 231 | // response, but the registry still remembers that those metrics had |
| 232 | // been exported before. For this example, we will now choose a |
| 233 | // different name. (In a real program, you would obviously not export |
nothing calls this directly
no test coverage detected