使用python编写自定义Prometheus Exporter

prometheus四种指标类型

Counter,Gauge,Summary,Histogram
Counter:计数器,只能递增,不能递减,通常配合rate(),increase()等函数计算速率或增量。值必须为数值,不能为负数。
Gauge:量度,可以递增也可以递减,通常用于度量当前值,如内存使用量,磁盘使用量等。值必须为数值,浮点数或整数。
Summary:摘要,用于度量请求的响应时间,如平均响应时间,最大响应时间,最小响应时间等。值必须为数值。
Histogram:直方图,用于度量请求的响应时间,如平均响应时间,最大响应时间,最小响应时间等。值必须为数值。

一个简单的python脚本,获取交换分区信息,判断grafana容器是否存在

import subprocess
import psutil
import time
#从prometheus_client导入start_http_server,Gauge
from prometheus_client import start_http_server, Gauge

#定义指标
#指标内容分为三部分,名称,描述,标签,标签需要使用元组或字符串列表定义
swap_memory_total = Gauge('linux_swap_memory_total', 'Total swap memory',['test_label'])

swap_memory_used = Gauge('linux_swap_memory_used', 'Used swap memory',['test_label'])

#额外添加一个指标,判断grafana容器是否正在运行
grafana_status = Gauge('grafana_status', 'Grafana status',['test_label'])


def collect_swap_metrics():
    #定义标签
    label = {'test_label': 'this is test label'}

    #判断grafana容器是否正在运行
    if subprocess.run('docker inspect grafana --format="{{.State.Running}}" > /dev/null 2>&1',shell=True):
        grafana_status.labels(**label).set(1)
    else:
        print("Grafana is not running")
        grafana_status.labels(**label).set(0)


    #获取交换分区信息
    swap = psutil.swap_memory()
    #调用labels方法设置标签,set方法设置指标值必须为数字
    #使用**kwargs语法,将标签字典中的键值对作为参数传递给labels方法,相当于调用swap_memory_total.labels(test_label='this is test label')
    swap_memory_total.labels(**label).set(swap.total)
    swap_memory_used.labels(**label).set(swap.used)


if __name__ == '__main__':
    #暴露端口8888
    start_http_server(8888)
    print("Exporter started at http://localhost:8888/metrics")

    while True:
        #调用指标采集函数
        collect_swap_metrics()
        #间隔10秒暴露一次数据
        time.sleep(10)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值