Prometheus之PushGateway

简介

PushGateway 使用场景:

  • Prometheus 采用定时 Pull 模式,可能由于子网络或者防火墙的原因,不能直接拉取各个 Target 的指标数据,此时可以采用各个 Target 往 PushGateway 上 Push 数据,然后 Prometheus 去 PushGateway 上定时 pull。

  • 其次在监控各个业务数据时,需要将各个不同的业务数据进行统一汇总,此时也可以采用 PushGateway 来统一收集,然后 Prometheus 来统一拉取。

Pushgateway并不是将Prometheus的pull改成了push,它只是允许用户向他推送指标信息,并记录。而Prometheus每次从 Pushgateway拉取的数据并不是期间用户推送上来的所有数据,而是最后一次push上来的数据。所以设置推送时间与Prometheus拉取的时间相同(<=)一般是较好的方案。

部署

docker安装

$ docker pull prom/pushgateway
$ docker run -d --name=pushgateway -p 9091:9091 prom/pushgateway

部署完成后,在浏览器输入 http://$IP:9091 即可看到程序界面

实现

pushgateway的数据推送支持两种方式,Prometheus Client SDK推送和API推送。

下面以 Client SDK推送进行讲解
Prometheus本身提供了支持多种语言的SDK,可通过SDK的方式,生成相关的数据,并推送到pushgateway,这也是官方推荐的方案。
目前的SDK覆盖语言有官方的:

  • Go

  • Java or Scala

  • Python

  • Ruby

也有许多第三方的,详情可参见此链接:https://prometheus.io/docs/instrumenting/clientlibs/

本示例以python为例,讲解SDK的使用

from prometheus_client import Counter,Gauge,push_to_gateway
from prometheus_client.core import CollectorRegistry

registry = CollectorRegistry()
data1 = Gauge('gauge_test_metric','This is a gauge-test-metric',['method','path','instance'],registry=registry) 
data1.labels(method='get',path='/aaa',instance='instance1').inc(3)

push_to_gateway('10.12.61.3:9091', job='alex-job',registry=registry)

大概逻辑就是:

  • 创建相关的指标,类型为Gauge。其中“gauge_test_metric”为指标名称,'This is a gauge-test-metric'为指标注释,['method','path','instance'] 为指标相关的label。

  • 添加相关的label信息和指标value 值。

  • push数据到pushgateway,'10.12.61.3:9091'为发送地址,job指定该任务名称。

以上代码产生的指标数据等同如下 :

# HELP gauge_test_metric This is a gauge-test-metric
# TYPE gauge_test_metric gauge
gauge_test_metric{instance="instance1",method="get",path="/aaa"} 3.0

配置

Pushgateway只是指标的临时存放点,最终我们需要通过Prometheus将其存放到时间序列数据库里。对此,我们需要在Prometheus上面创建一个job。

- job_name: 'pushgateway'
        honor_labels: true
        static_configs:
          - targets:
            - '10.12.61.3:9091'

目标任务正常启动后,可在prometheus查看到相关的指标数据

posted on 2023-05-30 18:18  萌兰三太子  阅读(526)  评论(0)    收藏  举报  来源

导航