You need to enable JavaScript to run this app. OpenTelemetry Python Metric Counter未被Prometheus采集及CLI埋点疑问
优惠活动
大模型
产品
解决方案
定价
更多

OpenTelemetry Python Metric Counter未被Prometheus采集及CLI埋点疑问

短生命周期CLI应用的OpenTelemetry Instrumentation问题

我编写了一个简单的Python CLI应用,用于学习Instrumentation技术。目标是通过Metric Counter统计应用的运行次数,但遇到两个问题:

  1. 每次重启应用后,Counter都会被重置为0;
  2. 应用结束过快,Prometheus无法采集到数据——添加time.sleep(5)后偶尔能成功但不稳定,不添加则完全无法采集,即使将prometheus.yml的scrape interval设为1s也无效。

疑问

  1. Instrumentation是否主要适用于Web应用这类持续运行的长生命周期应用?能否用于执行完任务即终止的CLI应用?
  2. 如何解决Prometheus无法快速采集短生命周期CLI应用Metric数据的问题?

附应用代码app.py

from opentelemetry import metrics
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import (
    ConsoleMetricExporter,
    PeriodicExportingMetricReader,
)

from opentelemetry.exporter.prometheus import PrometheusMetricReader
from opentelemetry.sdk.resources import SERVICE_NAME, Resource

import time

# Service name is required for most backends
resource = Resource(attributes={
    SERVICE_NAME: "my-python-app-service"
})

# Start Prometheus client
start_http_server(port=8000, addr="localhost")

# Initialize PrometheusMetricReader which pulls metrics from the SDK
# on-demand to respond to scrape requests
reader = PrometheusMetricReader()
provider = MeterProvider(resource=resource, metric_readers=[reader])
metrics.set_meter_provider(provider)

meter = provider.get_meter("your-meter-name")

def counter():
    counter = meter.create_counter(name="some-prefix-counter", description="TODO")

    # while True:
    counter.add(1)
    time.sleep(5) # if I remove this prometheus won't pick up any data I think because the scrape is not even run yet?

counter()

附Prometheus配置文件prometheus.yml

# my global config
global:
  scrape_interval: 1s # Set the scrape interval to every 15 seconds. Default is every 1 minute.

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: "prometheus-demo"
    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

    static_configs:
      - targets: ["localhost:8000"]

解答

1. Instrumentation对CLI应用的适用性

Instrumentation并非仅针对长生命周期应用,短生命周期的CLI工具完全可以使用,但需要适配其一次性运行的特性:

  • 长生命周期应用(如Web服务)持续运行,Prometheus通过定期拉取获取指标;
  • CLI应用是一次性执行,拉取模式无法保证Prometheus在应用退出前完成采集,且内存中的指标会随进程终止丢失,所以需要调整指标的存储和上报方式。

2. 解决Prometheus采集问题的方案

针对短生命周期应用的特性,推荐以下两种可靠方案:

方案一:改用PushGateway推送指标

Prometheus的拉取模式依赖目标服务在线,而PushGateway可以接收短生命周期应用主动推送的指标,再由Prometheus从PushGateway拉取,确保数据不会丢失。

  • 步骤:
    1. 启动PushGateway服务:docker run -p 9091:9091 prom/pushgateway
    2. 修改应用代码,将指标推送到PushGateway(同时解决Counter重置问题):
      from prometheus_client import Counter, push_to_gateway, CollectorRegistry
      import os
      
      # 创建注册表和Counter
      registry = CollectorRegistry()
      counter = Counter('some_prefix_counter', '统计应用运行次数', registry=registry)
      
      def update_counter():
          # 从文件持久化读取历史计数
          counter_file = 'counter_value.txt'
          prev_count = 0
          if os.path.exists(counter_file):
              with open(counter_file, 'r') as f:
                  prev_count = int(f.read().strip())
          
          # 更新计数并写入文件
          new_count = prev_count + 1
          with open(counter_file, 'w') as f:
              f.write(str(new_count))
          
          # 推送计数到PushGateway
          counter.inc(new_count)
          push_to_gateway('localhost:9091', job='my-python-app-service', registry=registry)
      
      update_counter()
      
    3. 修改Prometheus配置,添加对PushGateway的采集:
      scrape_configs:
        - job_name: "prometheus-demo"
          static_configs:
            - targets: ["localhost:8000"]
        - job_name: "pushgateway"
          static_configs:
            - targets: ["localhost:9091"]
      
方案二:持久化指标数据

如果不需要实时推送,可将Counter值持久化到外部存储(如文件、数据库),每次启动应用时读取历史值再累加,避免重启重置。同时可以在应用退出前主动触发Prometheus采集(但这种方式不如推送可靠)。

  • 核心逻辑:每次运行前读取外部存储的计数,加1后重新写入,再将新的计数上报。

内容的提问来源于stack exchange,提问作者Harts

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 12:07:15