CollectAndFormat collects the metrics identified by `metricNames` and returns them in the given format.
(c prometheus.Collector, format expfmt.FormatType, metricNames ...string)
| 236 | |
| 237 | // CollectAndFormat collects the metrics identified by `metricNames` and returns them in the given format. |
| 238 | func CollectAndFormat(c prometheus.Collector, format expfmt.FormatType, metricNames ...string) ([]byte, error) { |
| 239 | reg := prometheus.NewPedanticRegistry() |
| 240 | if err := reg.Register(c); err != nil { |
| 241 | return nil, fmt.Errorf("registering collector failed: %w", err) |
| 242 | } |
| 243 | |
| 244 | gotFiltered, err := reg.Gather() |
| 245 | if err != nil { |
| 246 | return nil, fmt.Errorf("gathering metrics failed: %w", err) |
| 247 | } |
| 248 | |
| 249 | gotFiltered = filterMetrics(gotFiltered, metricNames) |
| 250 | |
| 251 | var gotFormatted bytes.Buffer |
| 252 | enc := expfmt.NewEncoder(&gotFormatted, expfmt.NewFormat(format)) |
| 253 | for _, mf := range gotFiltered { |
| 254 | if err := enc.Encode(mf); err != nil { |
| 255 | return nil, fmt.Errorf("encoding gathered metrics failed: %w", err) |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | return gotFormatted.Bytes(), nil |
| 260 | } |
| 261 | |
| 262 | // convertReaderToMetricFamily would read from a io.Reader object and convert it to a slice of |
| 263 | // dto.MetricFamily. |