采集Python-GC指标
更新时间:2026-07-08
背景
OTel Python Runtime Metrics 默认没有 GC 次数、平均 GC 耗时的指标。
因此需要通过 自定义采集 来补充。
最佳实践
步骤 1:创建 utils.py 文件
Plain Text
11// utils.py
22
33import gc
44import time
55
66from opentelemetry import metrics
77
88
99def collect_gc_metrics():
1010 meter = metrics.get_meter("monitor", "1.0.0")
1111
1212 gc_duration = meter.create_counter(
1313 name="process.runtime.cpython.gc.duration",
1414 description="Runtime cpython GC duration per generation",
1515 unit="s",
1616 )
1717 gc_counter = meter.create_counter(
1818 name="process.runtime.cpython.gc.collections",
1919 description="Number of GC collections per generation",
2020 )
2121
2222 gc_start_times = {}
2323
2424 def gc_callback(phase, info):
2525 gen = info.get("generation")
2626 if phase == "start":
2727 gc_start_times[gen] = time.perf_counter()
2828 elif phase == "stop":
2929 start = gc_start_times.pop(gen, None)
3030 gc_counter.add(1, attributes={"count": gen})
3131 if start is not None:
3232 duration = time.perf_counter() - start
3333 gc_duration.add(duration, attributes={"count": gen})
3434
3535 gc.callbacks.append(gc_callback)
步骤 2:在主程序中使用此方法,并通过 Python 语言应用接入文档中的命令行参数启动应用即可
评价此篇文章
