Resettable counters with codahale metrics

Here’s a quick tutorial on how to implement counter metrics from codahale that resets after being reported.

Step 1

Register a gauge that increments a Counter and returns the current value while decrementing that value from the existing counter. This operation is thread safe.

1
2
3
4
5
6
7
8
9
metricsRegistry.register("my_resettable_gauge", new Gauge() {
    @Override
    public Long getValue() {
        Counter c = metrics.counter("my_counter_not_reported");
        long count = c.getCount();
        c.dec(count);
        return count;
    }
});

Note: You will have to make sure this is only registered once in your application lifecycle as repeated calls for the same gauge name will result in an Exception being thrown.

Step 2 (Optional)

You can also prevent the actual Counter metric from being reported as well, so as to not clutter up your metrics view by adding a filter.

1
2
3
4
5
6
GraphiteReporter.forRegistry(registry).filter(new MetricFilter() {
    @Override
    public boolean matches(String name, Metric metric) {
        return !name.contains("not_reported");
    }
}).build(client);