Home > Enterprise >  How to update metrics regularly using prometheus-flask-exporter?
How to update metrics regularly using prometheus-flask-exporter?

Time:02-08

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')

CodePudding user response:

I am not sure you understood how Prometheus works. By default Prometheus fetches the metrics from the target(s) every 15 seconds, but you can set a different interval. So it will call your endpoint every 15 seconds to retrieve the metrics, unless you decide otherwise. Your endpoint is purely passive and responds to incoming connections as they happen.

If what you want is to collect metrics every 5 seconds, then you have to edit your YAML configuration file on the Prometheus machine. The Flask app does not need changing.

CodePudding user response:

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')
  •  Tags:  
  • Related