Feedback

Chat Icon

Observability with Prometheus and Grafana

A Complete Hands-On Guide to Operational Clarity in Cloud-Native Systems

Instrumentation with Prometheus in Practice
67%

Counters: Tracking Metrics that Only Go Up

In the following example, we start by instantiating the Flask application and defining the Prometheus counters:

  • home_page_visits: to track the number of visits to the home page (/ endpoint).
  • about_page_visits: to track the number of visits to the about page (/about endpoint).

Using the following HELP descriptions:

  • Number of visits to the home page
  • Number of visits to the about page

The TYPE of both metrics is counter, since they are monotonically increasing metrics.

This is the code:

# Create a Flask application
app = Flask(__name__)

# Define Prometheus counters
home_counter = Counter(
    'home_page_visits',
    'Number of visits to the home page'
)

about_counter = Counter(
    'about_page_visits',
    'Number of visits to the about page'
)

When scraping the /metrics endpoint, Prometheus will see the following output for the two counters:

# HELP home_page_visits_total Number of visits to the home page
# TYPE home_page_visits_total counter
home_page_visits_total 0.0 # Or higher value if incremented

# HELP about_page_visits_total Number of visits to the about page
# TYPE about_page_visits_total counter
about_page_visits_total 0.0 # Or higher value if incremented

Next, we create two routes for the home and about pages:

@app.route('/')
def home():
    """ Route for the home page """
    # Increment the counter for the home page visits
    home_counter.inc()
    return "

Welcome to the Home Page

"
@app.route('/about') def about(): """ Route for the about page """ # Increment the counter for the about page visits about_counter.inc() return "

Welcome to the About Page

"

Notice that we increment the counters home_counter and about_counter every time a request is made to the home and about pages, respectively.

Finally, we expose the Prometheus metrics endpoint:

@app.route('/metrics')
def metrics():
    """ Expose the Prometheus metrics """
    return Response(
        generate_latest(),
        mimetype=CONTENT_TYPE_LATEST
    )

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=3000)

Use the following command to create the full app (on server1):

cat <<EOF > /prometheus-python-example/using_counters

Observability with Prometheus and Grafana

A Complete Hands-On Guide to Operational Clarity in Cloud-Native Systems

Enroll now to unlock all content and receive all future updates for free.