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)