Monitoring apps with Prometheus

The source code for this section is contained in the 04_03 branch of the GitHub repository for this course.

OpenShift includes the Prometheus project, used to observe applications in real time. Software developers can not only keep an eye on the memory and disk space used by their applications, but Prometheus makes it trivial to add counters for any kind of metric that makes sense to your applications.

Instrumenting Applications

The first step in application instrumentation consists in exporting the required metrics to Prometheus. Many programming languages, such as C#, Python, Java, and JavaScript, and web application frameworks like ASP.NET or Quarkus, include Prometheus-compatible libraries that automatically export data in a format compatible with Prometheus. The endpoints used to export that data usually have the /metrics URL.

package main

import (
	"github.com/prometheus/client_golang/prometheus" (1)
	"github.com/prometheus/client_golang/prometheus/promauto"
	"github.com/prometheus/client_golang/prometheus/promhttp"

	"fmt"
	"net/http"
)

var (  (2)
	example_counter = promauto.NewCounter(prometheus.CounterOpts{
		Name: "example_counter",
		Help: "An example of a Prometheus counter",
	})
)

func main() {
	r := prometheus.NewRegistry()
	r.MustRegister(example_counter)

	http.HandleFunc("/", Handler)
	http.Handle("/metrics", promhttp.Handler())  (3)
	http.ListenAndServe("0.0.0.0:8080", nil)
}

func Handler(w http.ResponseWriter, r *http.Request) {
	example_counter.Inc()
	fmt.Println("Handler executing")
	fmt.Fprintf(w, "The simplest API ever!")
}
1 Importing the Prometheus client library for the Go programming language.
2 Creating a new Prometheus counter.
3 Exporting the data to Prometheus using the /metrics endpoint
The source code of this application is available on the akosma/simple-go-api project on GitLab.

Prometheus gathers data from your application at regular intervals, providing an almost real-time trace of your application. Developers and system operators can use this information to understand the usage patterns of the application, and react properly to future events.

Observing Applications

Prometheus is an open source project that includes a query language called PromQL, used to synthesize and analyze information stored in a Prometheus database. The OpenShift web console includes support for entering PromQL queries, showing the current and historical values of any metric used to track the application.

prometheus metrics
Figure 1. Viewing Prometheus metrics directly on the OpenShift console

Using Grafana

Another common tool used together with Prometheus is Grafana, a web-based visualization tool that natively understands Prometheus data. You can launch an instance of Grafana in your cluster and show Prometheus data in real time.