Skip to content

Instantly share code, notes, and snippets.

@tembleking
Created September 28, 2018 06:11
Show Gist options
  • Save tembleking/1ca0e0f35929682f9821f192c6fcb6ec to your computer and use it in GitHub Desktop.
Save tembleking/1ca0e0f35929682f9821f192c6fcb6ec to your computer and use it in GitHub Desktop.
Prometheus
const client = require('prom-client');
const express = require('express');
const server = express();
const register = new client.Registry();
// Probe every 5th second.
const intervalCollector = client.collectDefaultMetrics({prefix: 'node_', timeout: 5000, register});
const counter = new client.Counter({
name: "node_my_counter",
help: "This is my counter"
});
const gauge = new client.Gauge({
name: "node_my_gauge",
help: "This is my gauge"
});
const histogram = new client.Histogram({
name: "node_my_histogram",
help: "This is my histogram",
buckets: [0.1, 5, 15, 50, 100, 500]
});
const summary = new client.Summary({
name: "node_my_summary",
help: "This is my summary",
percentiles: [0.01, 0.05, 0.5, 0.9, 0.95, 0.99, 0.999]
});
const requestHistogram = new client.Histogram({
name: "request_histogram",
help: "Histogram for requests",
labelNames: ['status_code'],
buckets: [0.1, 5, 15, 50, 100, 500]
});
register.registerMetric(counter);
register.registerMetric(gauge);
register.registerMetric(histogram);
register.registerMetric(summary);
register.registerMetric(requestHistogram);
const rand = (low, high) => Math.random() * (high - low) + low;
setInterval(() => {
counter.inc(rand(0, 1));
gauge.set(rand(0, 15));
histogram.observe(rand(0, 10));
summary.observe(rand(0, 10));
}, 1000);
server.get('/metrics', (req, res) => {
res.set('Content-Type', register.contentType);
res.end(register.metrics());
});
// Middleware
function newObservableRequest(histogram, func) {
return (req, res) => {
let start = +new Date();
func(req, res);
let end = +new Date();
let elapsed = end - start;
let code = req.method === "GET" ? "200" : "400";
histogram.labels(code).observe(elapsed);
}
}
server.get('/', newObservableRequest(requestHistogram, (req, res) => {
console.log("GET");
res.end();
}));
server.post('/', newObservableRequest(requestHistogram, (req, res) => {
console.log("POST");
res.end();
}));
console.log('Server listening to 8080, metrics exposed on /metrics endpoint');
server.listen(8080);
package main
import (
"fmt"
"log"
"math/rand"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
counter = prometheus.NewCounter(
prometheus.CounterOpts{
Namespace: "golang",
Name: "my_counter",
Help: "This is my counter",
})
gauge = prometheus.NewGauge(
prometheus.GaugeOpts{
Namespace: "golang",
Name: "my_gauge",
Help: "This is my gauge",
})
histogram = prometheus.NewHistogram(
prometheus.HistogramOpts{
Namespace: "golang",
Name: "my_histogram",
Help: "This is my histogram",
})
summary = prometheus.NewSummary(
prometheus.SummaryOpts{
Namespace: "golang",
Name: "my_summary",
Help: "This is my summary",
})
)
func main() {
rand.Seed(time.Now().Unix())
histogramVec := prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "prom_request_time",
Help: "Time it has taken to retrieve the metrics",
}, []string{"time"})
prometheus.Register(histogramVec)
http.Handle("/metrics", newHandlerWithHistogram(promhttp.Handler(), histogramVec))
prometheus.MustRegister(counter)
prometheus.MustRegister(gauge)
prometheus.MustRegister(histogram)
prometheus.MustRegister(summary)
go func() {
for {
counter.Add(rand.Float64() * 5)
gauge.Add(rand.Float64()*15 - 5)
histogram.Observe(rand.Float64() * 10)
summary.Observe(rand.Float64() * 10)
time.Sleep(time.Second)
}
}()
log.Fatal(http.ListenAndServe(":8080", nil))
}
func newHandlerWithHistogram(handler http.Handler, histogram *prometheus.HistogramVec) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
start := time.Now()
status := http.StatusOK
defer func() {
histogram.WithLabelValues(fmt.Sprintf("%d", status)).Observe(time.Since(start).Seconds())
}()
if req.Method == http.MethodGet {
handler.ServeHTTP(w, req)
return
}
status = http.StatusBadRequest
w.WriteHeader(status)
})
}
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import io.prometheus.client.*;
import io.prometheus.client.exporter.HTTPServer;
import io.prometheus.client.hotspot.DefaultExports;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Date;
public class Main {
private static double rand(double min, double max) {
return min + (Math.random() * (max - min));
}
public static void main(String[] args) {
Counter counter = Counter.build().namespace("java").name("my_counter").help("This is my counter").register();
Gauge gauge = Gauge.build().namespace("java").name("my_gauge").help("This is my gauge").register();
Histogram histogram = Histogram.build().namespace("java").name("my_histogram").help("This is my histogram").register();
Summary summary = Summary.build().namespace("java").name("my_summary").help("This is my summary").register();
Histogram requestHistogram = Histogram.build().namespace("java").name("request").help("Requets histogram").labelNames("statusCode").register();
DefaultExports.initialize();
try {
new HTTPServer("0.0.0.0", 8080, true);
} catch (IOException e) {
e.printStackTrace();
}
try {
HttpServer server = HttpServer.create(new InetSocketAddress("0.0.0.0", 80), 1000);
server.createContext("/", httpExchange -> {
Date start = new Date();
int statusCode = 200;
if (!"GET".equalsIgnoreCase(httpExchange.getRequestMethod())) {
statusCode = 400;
}
httpExchange.sendResponseHeaders(statusCode, 0);
httpExchange.getResponseBody().close();
httpExchange.close();
long elapsedTime = (new Date()).getTime() - start.getTime();
requestHistogram.labels(String.valueOf(statusCode)).observe(elapsedTime);
});
Thread bgThread = new Thread(() -> {
while (true) {
try {
counter.inc(rand(0, 5));
gauge.set(rand(-5, 10));
histogram.observe(rand(0, 5));
summary.observe(rand(0, 5));
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
bgThread.start();
server.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import prometheus_client as prom
import random
import time
from threading import Thread
from flask import Flask, request
from flask_prometheus import monitor
req_summary = prom.Summary('python_my_req_example', 'Time spent processing a request')
@req_summary.time()
def process_request(t):
time.sleep(t)
app = Flask("pyProm")
@app.route('/', methods=["GET", "POST"])
def hi():
if request.method == "GET":
return "OK", 200, None
return "Bad Request", 400, None
counter = prom.Counter('python_my_counter', 'This is my counter')
gauge = prom.Gauge('python_my_gauge', 'This is my gauge')
histogram = prom.Histogram('python_my_histogram', 'This is my histogram')
summary = prom.Summary('python_my_summary', 'This is my summary')
def thr():
while True:
counter.inc(random.random())
gauge.set(random.random() * 15 - 5)
histogram.observe(random.random() * 10)
summary.observe(random.random() * 10)
process_request(random.random() * 5)
time.sleep(1)
Thread(target=thr).start()
monitor(app, port=8080)
app.run(host="0.0.0.0", port=80)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment