Write Prometheus monitoring methods using Python
- 2020-12-18 01:51:54
- OfStack
To write Prometheus monitoring using python, you need to start the Prometheus cluster first. You can refer to / / www. ofstack. com article / 148895. htm installation. Implement the server side in python. Configure the request url in Prometheus, to which Prometheus will periodically issue requests for the data you want to return.
Prometheus monitoring is written using Python and Flask
Installation
pip install flask
pip install prometheus_client
Metrics
Prometheus offers four types of Metrics:
Counter
,
Gauge
,
Summary
and
Histogram
Counter
Counter can grow and is reset to 0 on program restart. It is often used for increasing the number of tasks, total processing time, number of errors, etc.
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")
Run the script and access youhost:5000/metrics
# HELP request_count Total request cout of the host
# TYPE request_count counter
request_count 3.0
Gauge
Gauge is similar to Counter except that the value of Gauge can be reduced. It is often used for temperature, utilization ratio and other indicators.
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")
Run the script and access youhost:5000/metrics
# HELP random_value Random value of the request
# TYPE random_value gauge
random_value 3.0
Summary/Histogram
The Summary/Histogram concept is quite complex, and exporter is very difficult to use, let alone.
LABELS
Use labels to distinguish the features of 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()
Prometheus monitoring was written using Python and asyncio
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 contains
requests_total = Counter("request_count", "Total request cout of the host") # Numerical only increased
random_value = Gauge("random_value", "Random value of the request") # The value can be large or small
@routes.get('/metrics')
async def metrics(request):
requests_total.inc() # Counter self-increment
# requests_total.inc(2)
data = prometheus_client.generate_latest(requests_total)
return web.Response(body = data,content_type="text/plain") # Returns the value of the counter
@routes.get("/metrics2")
async def metrics2(request):
random_value.set(random.randint(0, 10)) # Set the value to any value, but 1 Set for Integer or floating point number
return web.Response(body = prometheus_client.generate_latest(random_value),content_type="text/plain") # The value returned
@routes.get('/')
async def hello(request):
return web.Response(text="Hello, world")
# use labels To distinguish between metric The characteristics of the
c = Counter('requests_total', 'HTTP requests total', ['method', 'clientip']) # add lable the key .
c.labels('get', '127.0.0.1').inc() # For the different label The statistical
c.labels('post', '192.168.0.1').inc(3) # For the different label The statistical
c.labels(method="get", clientip="192.168.0.1").inc() # For the different label The statistical
g = Gauge('my_inprogress_requests', 'Description of gauge',['mylabelname'])
g.labels(mylabelname='str').set(3.6) #value Define your own , but 1 Set for Integer or floating point number
if __name__ == '__main__':
logging.info('server start : %s'% datetime.datetime.now())
app = web.Application(client_max_size=int(2)*1024**2) # create app , set the maximum size of the received image as 2M
app.add_routes(routes) # Add routing maps
web.run_app(app,host='0.0.0.0',port=2222) # Start the app
logging.info('server close : %s'% datetime.datetime.now())
conclusion