Prometheus Java simpleclient Custom Collector 指标是否应该在每个集合上实例化?

Should Prometheus Java simpleclient Custom Collector metrics be instantiated on every collection?

simpleclient Java README 示例中 Collector 如下所示:

class YourCustomCollector extends Collector {
  List<MetricFamilySamples> collect() {
    List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>();
    // With no labels.
    mfs.add(new GaugeMetricFamily("my_gauge", "help", 42));
    // With labels
    GaugeMetricFamily labeledGauge = new GaugeMetricFamily("my_other_gauge", "help", Arrays.asList("labelname"));
    labeledGauge.addMetric(Arrays.asList("foo"), 4);
    labeledGauge.addMetric(Arrays.asList("bar"), 5);
    mfs.add(labeledGauge);
    return mfs;
  }
}

// Registration
static final YourCustomCollector requests = new YourCustomCollector().register()

是否必须在每次调用 collect 时实例化指标,或者实例化一次然后在 collect 中调用 addMetric 是否合理?如果不是,这种方法会出现什么问题?

是的,MetricFamilies 应该(几乎)总是在每次收集时重新实例化。

would it be reasonable to instantiate them once and then just call addMetric in collect?

这不是线程安全的,您还需要做一些事情来跨集合清除它。