Prometheus

Get to know Prometheus

Prometheus is now widely used for collecting logs and metrics and then visualize it for checking performance, production issues.

Photo by Christian Paul Stobbe on Unsplash

Install Prometheus in Ubuntu

Get Prometheus package from https://prometheus.io/download/

tar xvzf prometheus*
cd prometheus*

Config prometheus yaml file

vim prometheus.yml

Example prometheus.yml file

# my global config
global:
scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
# scrape_timeout is set to the global default (10s).
# Alertmanager configuration
alerting:
alertmanagers:
- static_configs:
- targets:
# - alertmanager:9093
# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
# - "first_rules.yml"
# - "second_rules.yml"
# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
- job_name: 'prometheus'
# metrics_path defaults to '/metrics'
# scheme defaults to 'http'.
static_configs:
- targets: ['localhost:9090']

- job_name: 'node'
static_configs:
- targets: ['localhost:9100']
- job_name: 'myapp'
static_configs:
- targets:
- localhost:2112

View Prometheus metrics via GUI

Navigate to http://localhost:9090/graph for querying data

Example query for Node Exporter.

Prometheus Node Exporter

Prometheus HTTP API

Prometheus offers HTTP API for getting metadata about targets, delete metrics, or getting alerts information (https://prometheus.io/docs/prometheus/latest/querying/api/).

For example get Prometheus targets information : http://localhost:9090/api/v1/query?query=up&time=2021-01-14T07:10:00.001Z

Query Targets

Golang expose metrics to Prometheus

Download dependency

go get github.com/prometheus/client_golang

File main.go

package main

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

func recordMetrics() {
go func() {
for {
opsProcessed.Inc()
time.Sleep(2 * time.Second)
}
}()
}

var (
opsProcessed = promauto.NewCounter(prometheus.CounterOpts{
Name: "myapp_processed_ops_total",
Help: "The total number of processed events",
})
)

func main() {
recordMetrics()

http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":2112", nil)
}

Then run

go run main.go

Then add static config for prometheus.yml

- job_name: 'myapp'
static_configs:
- targets:
- localhost:2112

REFERENCES

Thanks for reading my post.

~~Happy programming guys~~

A passionate automation engineer who strongly believes in “A man can do anything he wants if he puts in the work”.

Get the Medium app