Prometheus学习系列11: 编写Prometheus Collector

优采云 发布时间: 2020-08-07 00:17

  在上一篇文章中,我写了一些官方出口商的用法. 在实际使用环境中,我们可能需要采集一些自定义数据. 目前,我们通常需要自己编写采集器.

  快速入门并编写一个演示性示例来编写代码

  from prometheus_client import Counter, Gauge, Summary, Histogram, start_http_server

# need install prometheus_client

if __name__ == '__main__':

c = Counter('cc', 'A counter')

c.inc()

g = Gauge('gg', 'A gauge')

g.set(17)

s = Summary('ss', 'A summary', ['a', 'b'])

s.labels('c', 'd').observe(17)

h = Histogram('hh', 'A histogram')

h.observe(.6)

start_http_server(8000)

import time

while True:

time.sleep(1)

  只需要一个py文件. 运行时,它将侦听端口8000并访问端口127.0.0.1:8000.

  效果图片

  

  实际上,已经编写了一个导出器,就这么简单,我们只需要配置prometheus来采集相应的导出器. 但是,我们导出的数据毫无意义.

  数据类型简介

  计数器是一种累积类型,只能增加,例如记录http请求总数或网络接收和发送的数据包的累积值.

  仪表盘: 仪表盘类型,适用于那些具有上升和下降,一般网络流量,磁盘读写等功能的仪表盘类型,该数据类型会随着波动和变化而使用.

  摘要: 基于抽样,统计信息在服务器上完成. 在计算平均值时,我们可能会认为异常值导致计算得出的平均值无法准确反映实际值,因此需要特定的点位置.

  直方图: 基于采样,统计在客户端上进行. 在计算平均值时,我们可能会认为异常值导致计算得出的平均值无法准确反映实际值,因此需要特定的点位置.

  采集内存并使用数据编写采集代码

  from prometheus_client.core import GaugeMetricFamily, REGISTRY

from prometheus_client import start_http_server

import psutil

class CustomMemoryUsaggeCollector():

def format_metric_name(self):

return 'custom_memory_'

def collect(self):

vm = psutil.virtual_memory()

#sub_metric_list = ["free", "available", "buffers", "cached", "used", "total"]

sub_metric_list = ["free", "available", "used", "total"]

for sub_metric in sub_metric_list:

gauge = GaugeMetricFamily(self.format_metric_name() + sub_metric, '')

gauge.add_metric(labels=[], value=getattr(vm, sub_metric))

yield gauge

if __name__ == "__main__":

collector = CustomMemoryUsaggeCollector()

REGISTRY.register(collector)

start_http_server(8001)

import time

while True:

time.sleep(1)

  公开数据情况

  

  部署代码并集成Prometheus

  # 准备python3 环境 参考: https://virtualenvwrapper.readthedocs.io/en/latest/

yum install python36 -y

pip3 install virtualenvwrapper

vim /usr/local/bin/virtualenvwrapper.sh

# 文件最前面添加如下行

# Locate the global Python where virtualenvwrapper is installed.

VIRTUALENVWRAPPER_PYTHON="/usr/bin/python3"

# 文件生效

source /usr/local/bin/virtualenvwrapper.sh

# 配置workon

[root@node01 ~]# echo "export WORKON_HOME=~/Envs" >>~/.bashrc

[root@node01 ~]# mkvirtualenv custom_memory_exporter

(custom_memory_exporter) [root@node01 ~]# pip install prometheus_client psutil

yum install python36-devel

(custom_memory_exporter) [root@node01 ~]# chmod a+x custom_memory_exporter.py

(custom_memory_exporter) [root@node01 ~]# ./custom_memory_exporter.py

# 测试是否有结果数据

[root@node00 ~]# curl http://192.168.100.11:8001/<br /><br />prometheus.yml 加入如下片段<br />  - job_name: "custom-memory-exporter"<br />    static_configs:<br />    - targets: ["192.168.100.11:8001"]<br /><br />[root@node00 prometheus]# systemctl restart prometheus <br />[root@node00 prometheus]# systemctl status prometheu

  查询效果图

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线