Add remove_matching() method for metric label deletion by hazel-shen · Pull Request #1121 · prometheus/client_python
Description
Fixes #1118
This PR introduces a new remove_by_labels() method to allow removing metric samples by matching a set of label values.
Changes
- Added
remove_by_labels()toMetricWrapperBasefor selective deletion of metrics by label. - Included validation for label names and types.
- Added safeguards for multi-process mode (warning issued if used).
- Kept the return value consistent with
remove(): returns None, and acts as a no-op if no series match.
Motivation
Currently, the Python client does not support removing metrics with specific label values without clearing the whole metric. This feature enables more granular control, which can be useful for scenarios such as:
- Cleaning up metrics for tenants after deprovisioning
- Removing outdated or irrelevant labeled data without impacting other metrics
Example Usage
from prometheus_client import Counter c = Counter('my_counter', 'Example counter', ['tenant', 'status']) c.labels(tenant='acme', status='ok').inc() c.labels(tenant='acme', status='fail').inc() # remove all series with tenant='acme', regardless of status c.remove_by_labels({'tenant': 'acme'})
@csmarchbanks Would you take a look when you have a chance?