python调用prometheus_python3+flask的prometheus监控示例

1.源码

#!/usr/bin/env python3

#测试prometheus的python接口

#参考文献 https://github.com/prometheus/client_python/blob/master/README.md

from prometheus_client import start_http_server, Summary

import random

import time

import os

import time

import datetime

import pymongo

import math

import logging

import logging.handlers

from flask import Flask, request, jsonify

from gevent.wsgi import WSGIServer

app = Flask(__name__)

# Create a metric to track time spent and requests made.

REQUEST_TIME = Summary('request_processing_seconds', 'Time spent processing request')

# Decorate function with metric.

@app.route("/t1")

@REQUEST_TIME.time()

def process_request():

"""A dummy function that takes some time."""

time.sleep(1)

return jsonify({"hi":"world"})

if __name__ == '__main__':

#这里是prometheus的监控端口,展示matrix信息

start_http_server(8000)

#启动flask

http_server = WSGIServer(('0.0.0.0', 6666), app)

http_server.serve_forever()

2.执行流程

2.1 启动py程序。

2.2 在浏览器开一个页面,打开http://localhost:8000 能看到度量参数

2.3 在浏览器开另一个页面,打开http://localhost:6666/t1,每刷新一下,就能看到2.2的参数变动一下。

2.4 可以增加更多的参数。

3. prometheus和k8s介绍  3.1 k8s是容器管理     https://blog.youkuaiyun.com/zhangxxxww/article/details/73547251  3.2 prometheus是开源监控,k8s也使用prometheus    http://www.cnblogs.com/vovlie/p/Prometheus_CONCEPTS.html

### 使用 Python 自定义 Prometheus 监控 Kubernetes 集群 为了实现自定义的 Prometheus 监控,可以借助 `prometheus_client` 库来创建并暴露指标。以下是具体方法: #### 安装依赖库 首先需要安装 `prometheus_client` 和其他可能需要用到的相关库: ```bash pip install prometheus-client flask requests kubernetes ``` #### 创建自定义监控逻辑 可以通过 Flask 或者简单的 HTTP 服务器暴露出一个 `/metrics` 接口供 Prometheus 抓取。 以下是一个完整的代码示例,用于收集 Kubernetes 节点上的 CPU 和内存使用情况,并将其作为自定义指标暴露给 Prometheus: ```python from prometheus_client import start_http_server, Gauge, Counter import time import os from kubernetes import client, config def initialize_k8s(): try: # 尝试加载集群内的 kubeconfig 文件 config.load_incluster_config() except Exception as e: # 如果失败,则尝试加载本地 kubeconfig 文件 config.load_kube_config() v1 = client.CoreV1Api() return v1 # 初始化 Prometheus 的指标对象 node_cpu_usage_gauge = Gauge('node_cpu_usage', 'CPU usage per node', ['node']) node_memory_usage_gauge = Gauge('node_memory_usage', 'Memory usage per node', ['node']) def collect_node_metrics(v1): nodes = v1.list_node().items for node in nodes: metadata = node.metadata status = node.status node_name = metadata.name # 假设我们已经有一个函数可以从 API 获取实际的资源利用率 cpu_usage_percent = get_cpu_usage(node_name) # 返回百分比值 memory_usage_bytes = get_memory_usage(node_name) # 返回字节数 # 更新指标值 node_cpu_usage_gauge.labels(node=node_name).set(cpu_usage_percent) node_memory_usage_gauge.labels(node=node_name).set(memory_usage_bytes) def get_cpu_usage(node_name): """模拟获取 CPU 利用率""" return float(os.popen(f"kubectl top node {node_name} | awk 'NR==2 {{print $3}}'").read()) def get_memory_usage(node_name): """模拟获取 Memory 利用率""" mem_str = os.popen(f"kubectl top node {node_name} | awk 'NR==2 {{print $4}}'").read() mem_value = int(mem_str.strip()[:-2]) * 1024 * 1024 # 单位转换为字节 return mem_value if __name__ == '__main__': # 启动 HTTP Server 并监听 /metrics 请求 start_http_server(8000) api_instance = initialize_k8s() while True: collect_node_metrics(api_instance) time.sleep(60) # 每隔一分钟更新一次数据 ``` 上述代码实现了以下几个功能: - **初始化 Kubernetes API**:通过 `kubernetes.client` 加载配置[^3]。 - **定义 Prometheus 指标**:使用 `Gauge` 类型分别表示节点的 CPU 和内存使用情况[^2]。 - **周期性采集数据**:调用 `collect_node_metrics` 函数定期从 Kubernetes 中提取节点状态信息[^4]。 #### 配置 Prometheus 抓取目标 在 Prometheus 的配置文件 `prometheus.yml` 中添加如下抓取配置项: ```yaml scrape_configs: - job_name: 'custom_python_exporter' static_configs: - targets: ['localhost:8000'] ``` 这会告诉 Prometheus 定期访问运行此 Python 程序的主机上的 `/metrics` 接口以获取最新数据。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值