gc_collector.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import gc
  2. import platform
  3. from typing import Iterable
  4. from .metrics_core import CounterMetricFamily, Metric
  5. from .registry import Collector, CollectorRegistry, REGISTRY
  6. class GCCollector(Collector):
  7. """Collector for Garbage collection statistics."""
  8. def __init__(self, registry: CollectorRegistry = REGISTRY):
  9. if not hasattr(gc, 'get_stats') or platform.python_implementation() != 'CPython':
  10. return
  11. registry.register(self)
  12. def collect(self) -> Iterable[Metric]:
  13. collected = CounterMetricFamily(
  14. 'python_gc_objects_collected',
  15. 'Objects collected during gc',
  16. labels=['generation'],
  17. )
  18. uncollectable = CounterMetricFamily(
  19. 'python_gc_objects_uncollectable',
  20. 'Uncollectable objects found during GC',
  21. labels=['generation'],
  22. )
  23. collections = CounterMetricFamily(
  24. 'python_gc_collections',
  25. 'Number of times this generation was collected',
  26. labels=['generation'],
  27. )
  28. for gen, stat in enumerate(gc.get_stats()):
  29. generation = str(gen)
  30. collected.add_metric([generation], value=stat['collected'])
  31. uncollectable.add_metric([generation], value=stat['uncollectable'])
  32. collections.add_metric([generation], value=stat['collections'])
  33. return [collected, uncollectable, collections]
  34. GC_COLLECTOR = GCCollector()
  35. """Default GCCollector in default Registry REGISTRY."""