client_java icon indicating copy to clipboard operation
client_java copied to clipboard

How to remove all metrics in the defaultRegistry

Open michaelschuett-tomtom opened this issue 1 year ago • 6 comments

Hello I was trying to figure out a good way to test some metrics in our application but I can't find a good way to clean out the default registry since it's not recreated during tests with mvn. This causes some tests to fail if for instance you use the same "test_metric" name twice. Does anyone have any example to clear out the registry as I couldn't find anything when looking through the code.

It looks like this is not possible based on this. So i guess my general question is how does one test with this library in use?

michaelschuett-tomtom avatar Apr 08 '24 14:04 michaelschuett-tomtom

You could create a new PrometheusRegistry registry = new PrometheusRegistry() for each test, and then register your metrics with that registry with .register(registry).

Does that work for you?

fstab avatar Apr 08 '24 15:04 fstab

This does work for me I had to do a small refactor so that our metric class by default uses the default registry but then during tests we optionally pass PrometheusRegistry() when initializing the metrics class. This works out well now since all of our metrics are centralized through this class but it would get a little messy if any custom metrics are added outside of it.

The above solves my immediate issue although it would be nice if a clear()/reset() function existed on the prometheus registry for just this purpose so we don't have to expose this for testing. If the defaultRegistry in PrometheusRegistry was exposed for users to overwrite that would also work but maybe this causes other issues?

michaelschuett-tomtom avatar Apr 08 '24 16:04 michaelschuett-tomtom

Hi, I also ran into this problem. Our metrics can be enabled or disabled based on a user's request so I need to unregister all registered collectors on such a request. It was possible in simpleclient using the clear() method but it is missing in the new 1.x version.

I will provide PR with the clear() method in a few minutes.

holubec-petr avatar Jun 18 '24 11:06 holubec-petr

Having a method to clear the registry would be really helpful for tests. Sure we can inject a new PrometheusRegistry instance but that requires further refactoring to adapt code that used to use simpleclient.

mimaison avatar Jun 24 '24 09:06 mimaison

PrometheusRegistry clear() / reset() methods will cause test issues when using JUnit5 in parallel execution mode.

dhoard avatar Jun 24 '24 12:06 dhoard

I'd love to see that added back as well. I was trying to upgrade the Java client in the Zookeeper project, however I am struggling to refactor the tests to make them work with a new PrometheusRegistry() before each run (see here).

der-eismann avatar Sep 20 '24 12:09 der-eismann