Prometheus-自定義Node_Exporter


標量(Scalar):一個浮點型的數字值

標量只有一個數字,沒有時序。

需要注意的是,當使用表達式count(http_requests_total),返回的數據類型,依然是瞬時向量。用戶可以通過內置函數scalar()將單個瞬時向量轉換為標量。

 

 

Prometheus-自定義Exporter-使用flask

#!/usr/bin/python
# -*- coding:utf-8 -*-
from flask import Flask,request,render_template,jsonify,Markup
import json

import logging
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
#定義一個全局字典
Show_Prometheus_Handler = {

}

app = Flask(__name__)

@app.route('/send_data',methods={'GET','POST'})
def send_data_to_dict():
    if request.method == "GET":
        return "method error,please use post method!"
    else:
        # 向dict里注冊
        global Show_Prometheus_Handler

        message = request.data
        #print(request.data)
        message_to_json = json.loads(message)
        metric = message_to_json.get("metric",None)
        type_staus = message_to_json.get("counterType",None)
        value = message_to_json.get("value",None)
        tags = message_to_json.get("tags",None)
        endpoint = message_to_json.get("endpoint",None)
        # 生成字段
        tag_list = []
        for tag in tags.split(","):
            t1,t2 = tag.split("=")
            tag_list.append('{0}="{1}"'.format(t1,t2))
        else:
            tag_list.append('%s="%s"' %("endpoint",endpoint))

        Show_Prometheus_Handler[metric] = '# HELP %s prometheus collected metric.\n# TYPE %s %s\n%s{%s} %s' %(metric,metric,type_staus.lower(),metric,",".join(tag_list),value)
        #print(Show_Prometheus_Handler[metric])

        return "ok"


@app.route('/metrics',methods=['GET','POST'])
def get_metrics():
    if request.method == "GET":
        metric_list = []
        for _,value in Show_Prometheus_Handler.items():
            metric_list.append(value)
        content_msg = Markup('{0}'.format("\n".join(metric_list)))
        return render_template('status.html',content=content_msg), {'Content-Type': 'text/plain; version=0.0.4'}

@app.route("/clean_metrics",methods=["GET","POST"])
def clean_metrics():
    if request.method == "GET":
        global Show_Prometheus_Handler
        Show_Prometheus_Handler = {}
        return "clean_ok"

if __name__ == '__main__':
    app.run("0.0.0.0",port=7777,threaded=True)

 需要注意的點  當Prometheus 出現Navtive Token的時候 需要在返回html的時候 加上 {'Content-Type': 'text/plain; version=0.0.4'}  Prometheus才能正常拉取數據.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM