Instrumentation with Prometheus in Practice
Gauges: Tracking Metrics that Go Up and Down
In addition to counters, Prometheus also supports gauges. Gauges are used to measure the current value of a metric, which can go up or down over time, in contrast to counters, which only increase.
A gauge is useful for tracking values that can change dynamically, such as the number of active connections to a server or the amount of free memory on a system, but also for tracking application-specific metrics.
In order to use it in our app, we will create two routes that add and remove numbers from a list. The gauge will track the length of the list.
We proceed by defining a gauge to track the size of a list:
# Define a gauge to track the size of a list
list_size_gauge = Gauge(
'list_size',
'Size of a list',
['list']
)
Then we create the routes (/add and /remove) to add and remove numbers from the list, respectively:
@app.route('/add/' )
def add(num1):
""" Route to add a number to my_list """
# add num1 to my_list
my_list.append(num1)
# set the gauge to the length of my_list
size = len(my_list)
list_size_gauge.labels('my_list').set(size)
# return a message
return f"Added {num1} to my_list"
@app.route('/remove/' )
def remove(num1):
""" Route to remove a number from my_list """
# remove num1 from my_list
my_list.remove(num1)
# set the gauge to the length of my_list
size = len(my_list)
list_size_gauge.labels('my_list').set(size)
# return a message
return f"Removed {num1} from my_list"
Run the following command to create the full app (on server1):
cat <<EOF > /prometheus-python-example/using_gauges.py
from flask import Flask, Response
from prometheus_client import (
Gauge,
generate_latest,
CONTENT_TYPE_LATEST
)
# Create a Flask application
app = Flask(__name__)
# Define a gauge to track the size of a list
list_size_gauge = Gauge(
'list_size',
'Size of a list',
['list']
)
my_list = []
@app.route('/add/' )
def add(num1):
""" Route to add a number to my_list """
# add num1 to my_list
my_list.append(num1)
# set the gauge to the length of my_listObservability with Prometheus and Grafana
A Complete Hands-On Guide to Operational Clarity in Cloud-Native SystemsEnroll now to unlock all content and receive all future updates for free.
