You need to enable JavaScript to run this app. Prometheus HTTP Server获取zcash_difficulty_gauge指标报错如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Prometheus HTTP Server获取zcash_difficulty_gauge指标报错如何解决

问题根因

你混淆了Prometheus Exporter指标暴露端点和Prometheus服务端API接口两个概念:

  • 你当前用prometheus_client启动的8094端口服务,是纯指标暴露的Exporter服务,仅支持返回纯文本格式的全量指标,本身不提供/api/v1/query这类PromQL查询接口。你请求不存在的路径时,服务默认还是返回全量指标文本,自然无法解析为JSON,也做不到单指标查询。
  • /api/v1/query是独立部署的Prometheus服务端才提供的API接口,需要先把你的Exporter配置为Prometheus的抓取目标后才能调用。

解决方案

方案1:直接从当前Exporter提取指定指标(无需部署Prometheus服务端)

直接请求Exporter的/metrics路径拉取全量指标,过滤目标指标即可,示例代码:

import requests

def get_zcash_difficulty():
    resp = requests.get("http://localhost:8094/metrics")
    resp.raise_for_status()
    # 逐行过滤目标指标
    for line in resp.text.split("\n"):
        if line.startswith("zcash_difficulty_gauge "):
            return float(line.split(" ")[1])
    return None

# 调用获取指标
print(get_zcash_difficulty())

如果需要通用解析Prometheus指标格式,也可以用prometheus-client自带的解析工具:

from prometheus_client.parser import text_string_to_metric_families
import requests

resp = requests.get("http://localhost:8094/metrics")
for family in text_string_to_metric_families(resp.text):
    if family.name == "zcash_difficulty_gauge":
        print(family.samples[0].value)

方案2:通过Prometheus服务端查询(支持PromQL复杂查询)

如果你需要用PromQL做更多查询操作,按照以下步骤操作:

  1. 部署Prometheus服务端,修改配置文件prometheus.yml,添加你的Exporter作为抓取目标:
scrape_configs:
  - job_name: "zcash_exporter"
    static_configs:
      - targets: ["localhost:8094"]
  1. 启动Prometheus服务端(默认端口为9090),再调用Prometheus服务端的查询接口:
import requests

query = "http://localhost:9090/api/v1/query?query=zcash_difficulty_gauge"
resp = requests.get(query)
resp.raise_for_status()
data = resp.json()
# 提取指标值
print(data['data']['result'][0]['value'][1])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 19:18:02