I'm creating a simple Flask webapp which should generate a random metric to be pulled by Prometheus. I'm using the prometheus-flask-exporter library which enabled me to set a metric.
Put simply, I want to know how can I configure custom metrics internally within flask so that they update at intervals from the '/metrics' endpoint of the flask app.
Not 'how often can I get prometheus to fetch a particular metric'
Currently I can't get a loop working within my flask app as the main class doesn't run if I have one.
This is just for a proof of concept, the custom metric can be anything.
My app.py:
from flask import Flask, render_template, request
from prometheus_flask_exporter import PrometheusMetrics
app = Flask(__name__)
metrics = PrometheusMetrics(app)
#Example of exposing information as a Gague metric:
info = metrics.info('random_metric', 'This is a random metric')
info.set(1234)
if __name__ == '__main__':
app.run(host='0.0.0.0')
I solved this problem by adding a background thread to do the work.
from flask import Flask
import requests
import time
import threading
class HealthChecker():
def __init__(self):
self.app = Flask(__name__)
@self.app.route('/', methods=['GET'])
def hello_world():
return "Hello world from Flask"
self.metrics = PrometheusMetrics(self.app)
threading.Thread(target = self.pull_metric).start()
if __name__ == '__main__':
healthChecker = HealthChecker()
self.app.run(host='0.0.0.0')