采集python GC指标
更新时间:2025-10-28
背景
OTel Python Runtime Metrics 默认没有 GC 次数、平均 GC 耗时的指标。
因此需要通过 自定义采集 来补充。
最佳实践
步骤1:创建utils.py文件
Python
1// utils.py
2
3import gc
4import time
5
6from opentelemetry import metrics
7
8
9def collect_gc_metrics():
10 meter = metrics.get_meter("monitor", "1.0.0")
11
12 gc_duration = meter.create_counter(
13 name="process.runtime.cpython.gc.duration",
14 description="Runtime cpython GC duration per generation",
15 unit="s",
16 )
17 gc_counter = meter.create_counter(
18 name="process.runtime.cpython.gc.collections",
19 description="Number of GC collections per generation",
20 )
21
22 gc_start_times = {}
23
24 def gc_callback(phase, info):
25 gen = info.get("generation")
26 if phase == "start":
27 gc_start_times[gen] = time.perf_counter()
28 elif phase == "stop":
29 start = gc_start_times.pop(gen, None)
30 gc_counter.add(1, attributes={"count": gen})
31 if start is not None:
32 duration = time.perf_counter() - start
33 gc_duration.add(duration, attributes={"count": gen})
34
35 gc.callbacks.append(gc_callback)
步骤2:在主程序中使用此方法,并通过python语言应用接入文档中的命令行参数启动应用即可
