Feedback

Chat Icon

Observability with Prometheus and Grafana

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

Instrumenting Applications with Prometheus
65%

How Prometheus Instrumentation Works

Prometheus provides a structured approach to software instrumentation through its client libraries, available in multiple programming languages. Developers embed these libraries directly into their application’s codebase to expose metrics in a Prometheus-compatible format.

For example, in a Go application, a simple counter that increments with each request can be instrumented using the Prometheus Go client library:

package main

import (
    "net/http"
    "github.com/prometheus/client_golang/prometheus"
    "github.com/prometheus/client_golang/prometheus/promhttp"
)

// Define a Prometheus counter vector for tracking total HTTP requests,
// labeled by HTTP status code.
var (
    requestsTotal = prometheus.NewCounterVec(
        prometheus.CounterOpts{
            Name: "requests_total",
            Help: "Total number of requests.",
        },
        []string{"code"},
    )
)

// Register the counter vector with Prometheus.
func init() {
    prometheus.MustRegister(requestsTotal)
}

func main() {
    // Expose the default Prometheus metrics endpoint.
    http.Handle("/metrics", promhttp.Handler())

    // Define a handler for the root path.
    // Increment the counter for HTTP 200 responses.
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        requestsTotal.WithLabelValues("200").Inc()
        w.Write([]byte("Hello, world!"))
    })

    http.ListenAndServe(":8080", nil)
}

In Python, the same functionality can be achieved using the Prometheus Python client library:

from prometheus_client import Counter, start_http_server
from flask import Flask
app = Flask(__name__)

# Define a Prometheus counter for tracking total HTTP requests,
# labeled by HTTP status code.
requests_total = Counter('requests_total', 'Total number of requests.', ['code'])

@app.route('/')
def hello():
    # Increment the counter for HTTP 200 responses.
    requests_total.labels(code='200').inc()
    return "Hello, world!"

if __name__ == '__main__':
    # Start the Prometheus metrics server on port 8080.

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.