使用Python编写Prometheus监控的方法

要使用python编写Prometheus监控,需要你先开启Prometheus集群。可以参考//www.jb51.net/article/148895.htm 安装。在python中实现服务器端。在Prometheus中配置请求网址,Prometheus会定期向该网址发起申请获取你想要返回的数据。

使用Python和Flask编写Prometheus监控

Installation

pip install flask
pip install prometheus_client

Metrics

Prometheus提供4种类型Metrics:Counter, Gauge, SummaryHistogram

Counter

Counter可以增长,并且在程序重启的时候会被重设为0,常被用于任务个数,总处理时间,错误个数等只增不减的指标。

import prometheus_client
from prometheus_client import Counter
from prometheus_client.core import CollectorRegistry
from flask import Response, Flask
app = Flask(__name__)
requests_total = Counter("request_count", "Total request cout of the host")
@app.route("/metrics")
def requests_count():
  requests_total.inc()
  # requests_total.inc(2)
  return Response(prometheus_client.generate_latest(requests_total),
          mimetype="text/plain")
@app.route('/')
def index():
  requests_total.inc()
  return "Hello World"
if __name__ == "__main__":
  app.run(host="0.0.0.0")

运行该脚本,访问youhost:5000/metrics

# HELP request_count Total request cout of the host
# TYPE request_count counter
request_count 3.0

Gauge

Gauge与Counter类似,唯一不同的是Gauge数值可以减少,常被用于温度、利用率等指标。

import random
import prometheus_client
from prometheus_client import Gauge
from flask import Response, Flask
app = Flask(__name__)
random_value = Gauge("random_value", "Random value of the request")
@app.route("/metrics")
def r_value():
  random_value.set(random.randint(0, 10))
  return Response(prometheus_client.generate_latest(random_value),
          mimetype="text/plain")
if __name__ == "__main__":
  app.run(host="0.0.0.0")

运行该脚本,访问youhost:5000/metrics

# HELP random_value Random value of the request
# TYPE random_value gauge
random_value 3.0

Summary/Histogram

Summary/Histogram概念比较复杂,一般exporter很难用到,暂且不说。

LABELS

使用labels来区分metric的特征

from prometheus_client import Counter
c = Counter('requests_total', 'HTTP requests total', ['method', 'clientip'])
c.labels('get', '127.0.0.1').inc()
c.labels('post', '192.168.0.1').inc(3)
c.labels(method="get", clientip="192.168.0.1").inc()

使用Python和asyncio编写Prometheus监控

from prometheus_client import Counter, Gauge
from prometheus_client.core import CollectorRegistry
REGISTRY = CollectorRegistry(auto_describe=False)
requests_total = Counter("request_count", "Total request cout of the host", registry=REGISTRY)
random_value = Gauge("random_value", "Random value of the request", registry=REGISTRY)
import prometheus_client
from prometheus_client import Counter,Gauge
from prometheus_client.core import CollectorRegistry
from aiohttp import web
import aiohttp
import asyncio
import uvloop
import random,logging,time,datetime
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
routes = web.RouteTableDef()
# metrics包含
requests_total = Counter("request_count", "Total request cout of the host") # 数值只增
random_value = Gauge("random_value", "Random value of the request") # 数值可大可小
@routes.get('/metrics')
async def metrics(request):
  requests_total.inc()   # 计数器自增
  # requests_total.inc(2)
  data = prometheus_client.generate_latest(requests_total)
  return web.Response(body = data,content_type="text/plain")  # 将计数器的值返回
@routes.get("/metrics2")
async def metrics2(request):
  random_value.set(random.randint(0, 10))  # 设置值任意值,但是一定要为 整数或者浮点数
  return web.Response(body = prometheus_client.generate_latest(random_value),content_type="text/plain")  # 将值返回
@routes.get('/')
async def hello(request):
  return web.Response(text="Hello, world")
# 使用labels来区分metric的特征
c = Counter('requests_total', 'HTTP requests total', ['method', 'clientip']) # 添加lable的key,
c.labels('get', '127.0.0.1').inc()    #为不同的label进行统计
c.labels('post', '192.168.0.1').inc(3)   #为不同的label进行统计
c.labels(method="get", clientip="192.168.0.1").inc()  #为不同的label进行统计
g = Gauge('my_inprogress_requests', 'Description of gauge',['mylabelname'])
g.labels(mylabelname='str').set(3.6)  #value自己定义,但是一定要为 整数或者浮点数
if __name__ == '__main__':
  logging.info('server start:%s'% datetime.datetime.now())
  app = web.Application(client_max_size=int(2)*1024**2)  # 创建app,设置最大接收图片大小为2M
  app.add_routes(routes)   # 添加路由映射
  web.run_app(app,host='0.0.0.0',port=2222)  # 启动app
  logging.info('server close:%s'% datetime.datetime.now())

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对我们的支持。如果你想了解更多相关内容请查看下面相关链接

(0)

相关推荐

  • Python实现一个服务器监听多个客户端请求

    学习Python网络通信的时候发现书上只有一个服务端对应一个客户端的情形,于是自己想自己动手实现一个服务端响应多个客户端. 首先建立服务器的socket来监听客户端的请求: tcpSerSock=socket(AF_INET,SOCK_STREAM) tcpSerSock.bind(ADDR) tcpSerSock.listen(5) 这样服务器的监听socket就建好了. 接下来的思路是,如果要监听多个客户端,则 tcpSerSock.accept() #(accept()是阻塞式的) 必须放

  • python实现简易内存监控

    本例主要功能:每隔3秒获取系统内存,当内存超过设定的警报值时,获取所有进程占用内存并发出警报声.内存值和所有进程占用内存记入log,log文件按天命名. 1 获取cpu.内存.进程信息 利用WMI 简单说明下,WMI的全称是Windows Management Instrumentation,即Windows管理规范.它是Windows操作系统上管理数据和操作的基础设施.我们可以使用WMI脚本或者应用自动化管理任务等. 安装模块 WMI下载地址 win32com下载地址: 学会使用WMI 不错的

  • 使用Python监控文件内容变化代码实例

    利用seek监控文件内容,并打印出变化内容: #/usr/bin/env python #-*- coding=utf-8 -*- pos = 0 while True: con = open("a.txt") if pos != 0: con.seek(pos,0) while True: line = con.readline() if line.strip(): print line.strip() pos = pos + len(line) if not line.strip(

  • python实现内存监控系统

    本文实例为大家分享了python实现内存监控系统的具体代码,供大家参考,具体内容如下 思路:通过系统命令或操作系统文件获取到内存信息(linux 内存信息存在/proc/meminfo文件中,mac os 通过命令vm_stat命令可以查看) 并将获取到信息保存到数据库中,通过web将数据实时的展示出来.(获取数据-展示数据) 1.后台数据采集(获取数据) import subprocess import re import MySQLdb as mysql import time import

  • python脚本监控Tomcat服务器的方法

    文章出处:https://blog.csdn.net/sdksdk0/article/details/80933444 作者:朱培      ID:sdksdk0     -------------------------------------------------------------------------------------------- 对于最近的开发环境,偶尔会有挂掉的现象发生,然而并没有及时发现,下载需要添加一个监控功能,当服务挂掉的时候需要有邮件提醒,同时我们的系统每天晚

  • Python文件监听工具pyinotify与watchdog实例

    pyinotify库 支持的监控事件 @cvar IN_ACCESS: File was accessed. @type IN_ACCESS: int @cvar IN_MODIFY: File was modified. @type IN_MODIFY: int @cvar IN_ATTRIB: Metadata changed. @type IN_ATTRIB: int @cvar IN_CLOSE_WRITE: Writtable file was closed. @type IN_CLO

  • Python实现监控键盘鼠标操作示例【基于pyHook与pythoncom模块】

    本文实例讲述了Python实现监控键盘鼠标操作.分享给大家供大家参考,具体如下: # -*- coding: utf-8 -*- import pythoncom import pyHook import time def onMouseEvent(event): "处理鼠标事件" fobj.writelines('-' * 20 + 'MouseEvent Begin' + '-' * 20 + '\n') fobj.writelines("Current Time:%s\

  • 使用python编写监听端

    本文实例为大家分享了python编写监听端的具体代码,供大家参考,具体内容如下 import socket import time import sys import string import struct import errno import binascii #Definition ser_ip = 'localhost' ser_port = 15001 HEADER_LISTENER = "IIII" split_time = 4 class TcpClient: def

  • Python从ZabbixAPI获取信息及实现Zabbix-API 监控的方法

    Python编写从ZabbixAPI获取信息 此脚本用Python3.6执行是OK的. # -*- coding: utf-8 -*- import json import urllib.request, urllib.error, urllib.parse class ZabbixAPI: def __init__(self): self.__url = 'http://192.168.56.102/zabbix/api_jsonrpc.php' self.__user = 'admin' s

  • Python实现数据可视化看如何监控你的爬虫状态【推荐】

    今天主要是来说一下怎么可视化来监控你的爬虫的状态. 相信大家在跑爬虫的过程中,也会好奇自己养的爬虫一分钟可以爬多少页面,多大的数据量,当然查询的方式多种多样.今天我来讲一种可视化的方法. 关于爬虫数据在mongodb里的版本我写了一个可以热更新配置的版本,即添加了新的爬虫配置以后,不用重启程序,即可获取刚刚添加的爬虫的状态数据. 1.成品图 这个是监控服务器网速的最后成果,显示的是下载与上传的网速,单位为M.爬虫的原理都是一样的,只不过将数据存到InfluxDB的方式不一样而已, 如下图. 可以

  • 利用Prometheus与Grafana对Mysql服务器的性能监控详解

    概述 Prometheus是一个开源的服务监控系统,它通过HTTP协议从远程的机器收集数据并存储在本地的时序数据库上.它提供了一个简单的网页界面.一个功能强大的查询语言以及HTTP接口等等.Prometheus通过安装在远程机器上的exporter来收集监控数据,这里用到了以下两个exporter: node_exporter – 用于机器系统数据 mysqld_exporter – 用于Mysql服务器数据 Grafana是一个开源的功能丰富的数据可视化平台,通常用于时序数据的可视化.它内置了

  • Python利用pyHook实现监听用户鼠标与键盘事件

    本文以一段简单的监听鼠标.键盘事件的程序,实现获取用户的输入(比如登录某些网站的账号.密码)的功能.经测试,对于一台"裸奔"的电脑,完全能获取到用户输入的任何信息:但是如果安装了杀毒软件,就够呛了.具体实现方法如下: 一.代码部分:获取用户输入信息,并与截图一起保存到XX目录下 # -*- coding: utf-8 -*- # import pythoncom import pyHook import time import socket from PIL import ImageG

随机推荐