1 背景
當Prometheus自帶的exporter無法滿足實際需求時,需要我們自定義開發采集器,本篇文章主要介紹通過python開發自定義的exporter
2 環境准備
本文介紹的采集器用python語言編寫,利用docker部署
-
python版本
版本要求為3.x,本文腳本例子python為3.8
-
python依賴包
# prometheus所需依賴包 from prometheus_client import Gauge, start_http_server, Counter from prometheus_client.core import CollectorRegistry import prometheus_client # api接口所需依賴包 import uvicorn from fastapi import FastAPI from fastapi.responses import PlainTextResponse
-
docker版本
20.10.8
3 采集器開發部署
3.1 exporter開發
定義Prometheus的metrics,這里主要介紹最常用的兩種metrics
-
Gauge
第一種是最常用的metrics——Gauge,Gauge可任意賦值,代表是當前采集的值
example_G = Gauge("this is a metric name", "this is a metric describe", ["label1", "label2", "label3"], registry=REGISTRY) # 指標名稱,描述,標簽名稱
-
Counter
第二種Counter是一直累計增加的計數器,不能減少。一般用來記錄訪問總次數等
example_C = Gauge("this is a metric name", "this is a metric describe", ["label1", "label2", "label3"], registry=REGISTRY) # 指標名稱,描述,標簽名稱
本文例子exporter文件名為test_exporter.py,具體腳本例子如下:
#!/usr/bin/python3
# coding:utf-8
from prometheus_client import Gauge, start_http_server, Counter
from prometheus_client.core import CollectorRegistry
import prometheus_client
import uvicorn
from fastapi import FastAPI
from fastapi.responses import PlainTextResponse
# 定義api對象
app = FastAPI()
# 設置接口訪問路徑/metrics
# @app語法糖需要放在最終入口函數
@app.get('/metrics', response_class=PlainTextResponse)
def get_data():
'''
該函數為最終函數入口(采集數據函數),該例子模擬采集到數據標簽label1、label2和label3,數據data1
'''
# 定義client_python里提供的prometheus Gauge數據類型
REGISTRY = CollectorRegistry(auto_describe=False)
example_G = Gauge("this_is_a_metric_name", "this is a metric describe", ["label1", "label2", "label3"], registry=REGISTRY)
label1 = '111'
label2 = '222'
label3 = '333'
data1 = '444'
# 調用Gauge數據類型,把采集的數據放入到設定的example_G
example_G.labels(label1,label2,label3).set(data1)
# return需放在函數下最外層,否則返回的數據有缺失
return prometheus_client.generate_latest(REGISTRY)
# 用uvicorn調用接口,啟用端口為9330
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=9330, log_level="info")
在終端執行pip freeze > requirements.txt生成依賴包清單
fastapi==0.68.1
prometheus-client==0.11.0
uvicorn==0.15.0
3.2 docker部署
把寫好的腳本用docker打包
在./test目錄創建一個app目錄存放腳本test_exporter.py
把生成的requirements.txt放到./test目錄下
在./test目錄編寫Dockerfile
FROM python:3.9-alpine
RUN mkdir -p /test/app
COPY ./requirements.txt /app/requirements.txt
COPY ./app /test/app
WORKDIR /app
RUN pip install -r requirements.txt
CMD ["python", "/test/app/test_exporter.py"]
創建鏡像 docker image build -t test_exporter:v0.1 .
創建后可通過 docker images
查看生成的docker鏡像
運行exporter docker run -it -d --name test_exporter -p 9330:9330 test_exporter:v0.1
運行后可以通過 docker ps
查看容器啟動情況,docker logs (容器ID)
查看容器日志
采集器啟用后可以通過調用接口查看采集數據 http://localhost:9330/metrics
4 配置采集任務
修改prometheus.yml配置文件,添加采集任務(添加后需要重啟Prometheus)
scrape_configs:
- job_name: "test_exporter"
scrape_interval: 30s # 采集頻率為30s抓取一次
static_configs:
- targets: # 配置采集任務
- 127.0.0.1:9330
在Prometheus官方Graph中通過采集metric名查看采集數據
原創聲明
本文原創自作者:liu_kx,轉載請注明原文鏈接