自动采集编写(采集内存使用数据采集类代码暴露数据情况部署代码和集成查询 )
优采云 发布时间: 2021-08-30 17:01自动采集编写(采集内存使用数据采集类代码暴露数据情况部署代码和集成查询
)
在之前的文章中,我已经写过几个官方exporter的使用。在实际使用环境中,我们可能需要采集一些自定义数据。这个时候一般需要我们自己写采集器。
快速开始写一个介绍性的demo来写代码
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端口。
效果图
其实一个exporter已经写好了。就这么简单。我们只需要在prometheus中配置采集对应的exporter即可。但是,我们导出的数据毫无意义。
数据类型介绍
Counter 是一个累加类型,只能增加,比如记录http请求的总次数或者网络收发包的累计值。
Gauge:仪表盘类型,适用于有涨有跌、一般网络流量、磁盘读写等,有波动变化的数据类型使用。
总结:基于抽样,在服务器上完成统计。当我们统计平均值时,可能会认为异常值导致计算出的平均值不能准确反映实际值,需要具体的点位。
直方图:基于抽样,在客户端进行统计。当我们统计平均值时,可能会认为异常值导致计算出的平均值不能准确反映实际值,需要具体的点位。
采集Memory 使用数据编写采集类代码
暴露数据情况
部署代码并集成 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/
prometheus.yml 加入如下片段
- job_name: "custom-memory-exporter"
static_configs:
- targets: ["192.168.100.11:8001"]
[root@node00 prometheus]# systemctl restart prometheus
[root@node00 prometheus]# systemctl status prometheu
查询效果图