You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从HTTP响应提取值暴露为Prometheus自定义指标?Blackbox Exporter是否适用?

从API响应提取值转成Prometheus指标的解决方案

Blackbox Exporter能不能用?

不行。Blackbox Exporter的核心是做服务探测——比如检查API能不能访问、HTTP状态码对不对、响应时间多长,它没设计从响应体里提取自定义字段并转成指标的功能,所以你之前试了没成是正常的,找错工具了。

靠谱的解决方案有这几个:

1. 用Json Exporter(JSON响应首选)

如果你的API返回的是JSON格式(比如{"credit_used": 1234}),Json Exporter就是干这个的,步骤如下:

  • 写配置文件config.yml:
modules:
  license_credit:
    metrics:
      - name: license_credit_consumed
        path: "{.credit_used}" # 这里填对应要提取的JSON字段路径
        help: "当前许可证的信用消耗值"
        labels:
          api_endpoint: "license"
  • 启动Json Exporter:
./json_exporter --config.file=config.yml
  • 修改Prometheus的prometheus.yml,添加抓取任务:
scrape_configs:
  - job_name: 'license_credit'
    static_configs:
      - targets: ['localhost:7979'] # Json Exporter默认监听7979端口
    params:
      target: ['http://www.example.com/api/license'] # 填入你的API地址

重启Prometheus后,就能看到license_credit_consumed指标了。

2. 脚本+Node Exporter的文本收集器(灵活适配任意响应格式)

如果API返回XML、纯文本,或者需要加身份验证之类的逻辑,写个脚本提取值,再通过Node Exporter暴露是最灵活的:

  • 写脚本get_credit.sh(这里假设是JSON响应,要是别的格式,把jq换成grep/awk即可):
#!/bin/bash
# 抓取API响应并提取目标字段
CREDIT=$(curl -s http://www.example.com/api/license | jq '.credit_used')
# 将指标写入Node Exporter指定的目录
echo "license_credit_consumed $CREDIT" > /var/lib/node_exporter/textfile_collector/license_credit.prom
  • 给脚本加执行权限:chmod +x get_credit.sh
  • 设置定时任务,每分钟执行一次:* * * * * /path/to/get_credit.sh
  • 启动Node Exporter时添加参数,开启文本收集器:
./node_exporter --collector.textfile.directory=/var/lib/node_exporter/textfile_collector

之后Prometheus抓取Node Exporter的指标时,就能看到这个自定义指标了。

3. 自己写个简单的Python Exporter(复杂场景用)

如果需要处理多API聚合、复杂身份验证(比如带token请求),写个Python脚本当Exporter最方便:

from prometheus_client import start_http_server, Gauge
import requests
import time

# 定义Prometheus指标
LICENSE_CREDIT = Gauge('license_credit_consumed', '当前许可证的信用消耗值')

def fetch_credit():
    # 如需身份验证,可添加headers参数,比如headers={'Authorization': 'Bearer xxx'}
    response = requests.get('http://www.example.com/api/license')
    # 解析响应,这里按JSON格式处理,其他格式自行调整逻辑
    credit = response.json()['credit_used']
    LICENSE_CREDIT.set(credit)

if __name__ == '__main__':
    start_http_server(8000) # 监听8000端口
    while True:
        fetch_credit()
        time.sleep(60) # 每分钟更新一次指标

运行脚本后,Prometheus抓取http://localhost:8000/metrics就能拿到目标指标。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 20:40:21