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