首页 > 其他分享 >Prometheus自定义监控项

Prometheus自定义监控项

时间:2023-02-10 14:55:30浏览次数:33  
标签:exists 自定义 pid prometheus Prometheus client 监控 path crond

img# Prometheus自定义监控项

一、环境依赖

pip install prometheus-client
  • 默认会监控Jython,metadata等会造成对应干扰,作者习惯去除

捕获

import prometheus_client 

prometheus_client.REGISTRY.unregister(prometheus_client.GC_COLLECTOR)
prometheus_client.REGISTRY.unregister(prometheus_client.PLATFORM_COLLECTOR)
prometheus_client.REGISTRY.unregister(prometheus_client.PROCESS_COLLECTOR)

二、SDK编写

2.1 监控服务状态

  • 正常启停服务,该pid文件会随启停创建删除
  • 强杀情况(类似kill -9),pid文件并不会被删除
#已监控crond服务为例
#判断服务状态从两个维度触发
#1.该服务pid文件是否存在
#2.该服务是否被强杀,既存在pid文件但进程不存在
from prometheus_client import CollectorRegistry,Gauge,push_to_gateway
from time import sleep
from psutil import pid_exists
import os 

def crond(path:str):
    exists = os.path.exists(path) #检查是否存在服务的pid文件
    if exists:					  #如果存在就读取pid文件里面的进程号,去查询进程是否存在
        with open(path,'r') as f:
            for pid in f:		  #读取文件
                process = pid_exists(int(pid.rstrip('\n'))) #检查进程
                if process:       #为真则存在
                    return 1
                else:
                    return -1
    else:
        return 0
while True:
    path = '//var//run//crond.pid' #pid文件路径
    data = crond(path=path) #数值
    Registry = CollectorRegistry(auto_describe=False)#注册器
    Service = Gauge('crond_service','this is test gauge',['label'],registry=Registry)#自定义监控项
    Service.labels(label="crond").set(data) #打标签、传值
    push_to_gateway("http://127.0.0.1:9091",job='crond_service',registry=Registry)
    sleep(1) #控制采集频率

标签:exists,自定义,pid,prometheus,Prometheus,client,监控,path,crond
From: https://www.cnblogs.com/twitedfate/p/17108906.html

相关文章