Add clear() function to CollectorRegistry.
Hello! I was working with the prometheus_client python library and I noticed that there isn't a method for removing all collectors on a CollectorRegistry instance. Yet there is a method for removing single collectors from the registry.
I propose to add a function that removes all collectors from the registry.
This is an example code of the actual implementation:
from prometheus_client import Gauge, CollectorRegistry
# Create the registry
registry = CollectorRegistry()
# Create and set the gauges
g1 = Gauge("Metric1", "Description1", registry=registry)
g2 = Gauge("Metric2", "Description2", registry=registry)
g3 = Gauge("Metric3", "Description3", registry=registry)
g1.set(42)
g2.set(43)
g3.set(44)
# Remove the gauges from the registry manually
registry.unregister(g1)
registry.unregister(g2)
registry.unregister(g3)
This is the code expected after this proposed enhancement:
# Create the registry
registry = CollectorRegistry()
# Create and set the gauges
g1 = Gauge("Metric1", "Description1", registry=registry)
g2 = Gauge("Metric2", "Description2", registry=registry)
g3 = Gauge("Metric3", "Description3", registry=registry)
g1.set(42)
g2.set(43)
g3.set(44)
# Remove the gauges from the registry with one function call.
registry.clear()
I hope this addition will remove boilerplate when clearing registries.
Thanks for the issue!
What is the use case for removing everything like that? I ask as I wonder if the use case would be better served with a custom collector instead. That said, if a custom collector doesn't make sense I am not opposed to this functionality.
Hello!
Thanks for the response. I will explain my personal use case here: I'm making a simple library with a set and flush method of adding variables and writing them to a textfile (For later collection with Node Exporter). And for that, I use the default collector that comes in this repository. But after writing it to a Textfile I want to flush the CollectorRegistry to start all over again. This implementation is built so you just write the metrics with a function and flush them into a file. After that you can repeat the process with no boilerplate whatsoever. My actual method of achieving this implies iterating over all the values in the Registry and manually deleting them, so I thought a cleaning method would be a nice addition to the library.
I personally don't know if that implementation is better with a custom collector. But I was just writing this Issue to validate my idea for a future PR.