解决方案:prometheus学习系列十一: Prometheus 采集器的编写
优采云 发布时间: 2020-09-06 01:15普罗米修斯学习丛书11:普罗米修斯采集器准备
上面文章中已写明了几个官方出口商的使用。在实际使用环境中,我们可能需要采集一些自定义数据。目前,我们通常需要自己写采集器。
快速开始编写介绍性示例以编写代码
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并访问端口12 7. 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
查询效果图