• Stars
    star
    319
  • Rank 127,298 (Top 3 %)
  • Language
    Go
  • License
    Apache License 2.0
  • Created about 5 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Go modular http middleware to measure HTTP requests independent of metrics backend (with Prometheus and OpenCensus as backend implementations) and http framework/library

go-http-metrics Build Status Go Report Card GoDoc

go-http-metrics knows how to measure http metrics in different metric formats and Go HTTP framework/libs. The metrics measured are based on RED and/or Four golden signals, follow standards and try to be measured in a efficient way.

Table of contents

Metrics

The metrics obtained with this middleware are the most important ones for a HTTP service.

  • Records the duration of the requests(with: code, handler, method).
  • Records the count of the requests(with: code, handler, method).
  • Records the size of the responses(with: code, handler, method).
  • Records the number requests being handled concurrently at a given time a.k.a inflight requests (with: handler).

Metrics recorder implementations

go-http-metrics is easy to extend to different metric backends by implementing metrics.Recorder interface.

Framework compatibility middlewares

The middleware is mainly focused to be compatible with Go std library using http.Handler, but it comes with helpers to get middlewares for other frameworks or libraries.

When go-http-metrics is imported as a dependency, it will only import the libraries being used, this is safe because each lib/framework is in its own package. More information here and here

It supports any framework that supports http.Handler provider type middleware func(http.Handler) http.Handler (e.g Chi, Alice, Gorilla...). Use std.HandlerProvider

Getting Started

A simple example that uses Prometheus as the recorder with the standard Go handler.

package main

import (
    "log"
    "net/http"

    "github.com/prometheus/client_golang/prometheus/promhttp"
    metrics "github.com/slok/go-http-metrics/metrics/prometheus"
    "github.com/slok/go-http-metrics/middleware"
    middlewarestd "github.com/slok/go-http-metrics/middleware/std"
)

func main() {
    // Create our middleware.
    mdlw := middleware.New(middleware.Config{
        Recorder: metrics.NewRecorder(metrics.Config{}),
    })

    // Our handler.
    h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        w.Write([]byte("hello world!"))
    })
    h = middlewarestd.Handler("", mdlw, h)

    // Serve metrics.
    log.Printf("serving metrics at: %s", ":9090")
    go http.ListenAndServe(":9090", promhttp.Handler())

    // Serve our handler.
    log.Printf("listening at: %s", ":8080")
    if err := http.ListenAndServe(":8080", h); err != nil {
        log.Panicf("error while serving: %s", err)
    }
}

For more examples check the examples. default and custom are the examples for Go net/http std library users.

Prometheus query examples

Get the request rate by handler:

sum(
    rate(http_request_duration_seconds_count[30s])
) by (handler)

Get the request error rate:

rate(http_request_duration_seconds_count{code=~"5.."}[30s])

Get percentile 99 of the whole service:

histogram_quantile(0.99,
    rate(http_request_duration_seconds_bucket[5m]))

Get percentile 90 of each handler:

histogram_quantile(0.9,
    sum(
        rate(http_request_duration_seconds_bucket[10m])
    ) by (handler, le)
)

Options

Middleware Options

The factory options are the ones that are passed in the moment of creating the middleware factory using the middleware.Config object.

Recorder

This is the implementation of the metrics backend, by default it's a dummy recorder.

Service

This is an optional argument that can be used to set a specific service on all the middleware metrics, this is helpful when the service uses multiple middlewares on the same app, for example for the HTTP api server and the metrics server. This also gives the ability to use the same recorder with different middlewares.

GroupedStatus

Storing all the status codes could increase the cardinality of the metrics, usually this is not a common case because the used status codes by a service are not too much and are finite, but some services use a lot of different status codes, grouping the status on the \dxx form could impact the performance (in a good way) of the queries on Prometheus (as they are already aggregated), on the other hand it losses detail. For example the metrics code code="401", code="404", code="403" with this enabled option would end being code="4xx" label. By default is disabled.

DisableMeasureSize

This setting will disable measuring the size of the responses. By default measuring the size is enabled.

DisableMeasureInflight

This settings will disable measuring the number of requests being handled concurrently by the handlers.

Custom handler ID

One of the options that you need to pass when wrapping the handler with the middleware is handlerID, this has 2 working ways.

  • If an empty string is passed mdwr.Handler("", h) it will get the handler label from the url path. This will create very high cardnialty on the metrics because /p/123/dashboard/1, /p/123/dashboard/2 and /p/9821/dashboard/1 would have different handler labels. This method is only recomended when the URLs are fixed (not dynamic or don't have parameters on the path).

  • If a predefined handler ID is passed, mdwr.Handler("/p/:userID/dashboard/:page", h) this will keep cardinality low because /p/123/dashboard/1, /p/123/dashboard/2 and /p/9821/dashboard/1 would have the same handler label on the metrics.

There are different parameters to set up your middleware factory, you can check everything on the docs and see the usage in the examples.

Prometheus recorder options

Prefix

This option will make exposed metrics have a {PREFIX}_ in fornt of the metric. For example if a regular exposed metric is http_request_duration_seconds_count and I use Prefix: batman my exposed metric will be batman_http_request_duration_seconds_count. By default this will be disabled or empty, but can be useful if all the metrics of the app are prefixed with the app name.

DurationBuckets

DurationBuckets are the buckets used for the request duration histogram metric, by default it will use Prometheus defaults, this is from 5ms to 10s, on a regular HTTP service this is very common and in most cases this default works perfect, but on some cases where the latency is very low or very high due the nature of the service, this could be changed to measure a different range of time. Example, from 500ms to 320s Buckets: []float64{.5, 1, 2.5, 5, 10, 20, 40, 80, 160, 320}. Is not adviced to use more than 10 buckets.

SizeBuckets

This works the same as the DurationBuckets but for the metric that measures the size of the responses. It's measured in bytes and by default goes from 1B to 1GB.

Registry

The Prometheus registry to use, by default it will use Prometheus global registry (the default one on Prometheus library).

Label names

The label names of the Prometheus metrics can be configured using HandlerIDLabel, StatusCodeLabel, MethodLabel...

OpenCensus recorder options

DurationBuckets

Same option as the Prometheus recorder.

SizeBuckets

Same option as the Prometheus recorder.

Label names

Same options as the Prometheus recorder.

UnregisterViewsBeforeRegister

This Option is used to unregister the Recorder views before are being registered, this is option is mainly due to the nature of OpenCensus implementation and the huge usage fo global state making impossible to run multiple tests. On regular usage of the library this setting is very rare that needs to be used.

More Repositories

1

sloth

πŸ¦₯ Easy and simple Prometheus SLO (service level objectives) generator
Go
1,519
star
2

grafterm

Metrics dashboards on terminal (a grafana inspired terminal version)
Go
842
star
3

kubewebhook

Go framework to create Kubernetes mutating and validating webhooks
Go
521
star
4

agebox

Age based repository file encryption gitops tool
Go
161
star
5

goresilience

A library to improve the resilience of Go applications in an easy and flexible way
Go
146
star
6

ecs-exporter

Export AWS ECS cluster metrics to Prometheus
Go
136
star
7

kube-code-generator

Kubernetes code generator docker image
Go
66
star
8

k8s-webhook-example

Kubernetes production-ready admission webhook example
Go
64
star
9

brigadeterm

A simple terminal ui for brigade pipelining system
Go
63
star
10

go-jwt-example

Golang & jwt (Jason web token) example
Go
47
star
11

alertgram

Easy and simple prometheus alertmanager alerts on telegram
Go
40
star
12

rainbow-bash

Better bash prompt! you don't need zsh for cool prompts
Shell
39
star
13

Box2D-and-SFML-demo

Box2D and SFML Demo, with DebugDraw implemented with SFML
C++
34
star
14

kahoy

Simple Kubernetes raw manifests deployment tool
Go
32
star
15

iris

Pelican (the static blog generator) theme based in Flask webpage theme
CSS
31
star
16

tfe-drift

Automated Terraform cloud and enterprise drift detection
Go
31
star
17

reload

Simple managed reload mechanism for Go
Go
30
star
18

sloth-common-sli-plugins

Sloth common SLI plugins collection
Go
29
star
19

pygressbar

Flexible and customizable python progress bar
Python
27
star
20

redis-node-push-notifications-example

An example of using redis pub/sub for realtime client notifications with Redis, socket.io and node.js
JavaScript
24
star
21

gospinner

Make beautiful and fast spinners in Go
Go
19
star
22

algs4-mvn-repo

Maven repository for algorithms and data strcutures coursera course ( https://www.coursera.org/course/algs4partI )
19
star
23

prometheus-python

Prometheus metric system client for python
Python
18
star
24

bilrost

Kubernetes controller/operator to set up OAUTH2/OIDC security on any ingress based service
Go
18
star
25

devops-course

Devops course sources (Vagrant, Ansible & Docker )
Ruby
17
star
26

simple-ingress-external-auth

A very simple external authentication service for Kubernetes ingresses (ingress-nginx, traefik...)
Go
16
star
27

noglog

"Bring your own logger" replacement for github.com/golang/glog.
Go
13
star
28

go-prometheus-middleware

Go net/http configurable handler to measure requests using Prometheus metrics
Go
13
star
29

brigade-exporter

Exporter for brigade metrics
Go
11
star
30

terraform-provider-dataprocessor

Terraform provider for easy and clean data processing (JQ, YQ, Go plugins...).
Go
10
star
31

go-copy

Copy (http://copy.com) service library
Go
9
star
32

prometheus-statsd-integration-example

Simple example of statsd and prometheus integration
Shell
9
star
33

django-chameleon

Django theme (template) changer app
Python
9
star
34

favorshare-orchestration

An Ansible complete example for provisioning a whole project
Shell
8
star
35

pod-exec-guard-kubewebhook-tutorial

Kubernetes webhook development (validating admission webhook) tutorial using kubewebhook
Go
8
star
36

khronos

Modern replacement of cron for microservice architecture.
Go
6
star
37

resilience-demo

A resilience demo with different scenarios
Go
6
star
38

tracing-example

Simple Kubernetes tracing example and experiment
Go
6
star
39

flaskit

Simple git front-end powered by Flask and Dulwich
JavaScript
6
star
40

go-helm-template

Simple go library to run Helm template without executing Helm
Go
6
star
41

ragnarok-old

The new way of injecting failure
Go
5
star
42

terraform-provider-goplugin

A Terraform provider to create terraform providers 🀯, but easier and faster! (By using Small go plugins)
Go
5
star
43

external-dns-aws-migrator

Utility to adopt AWS route53 entries (record sets) so the external-dns can track and update them based on Kubernetes ingresses
Go
4
star
44

imagepull-controller-workshop

A Kubernetes controller workshop where we are creating a imagepullsecret-patcher controller
Go
4
star
45

tfe-drift-action

tfe-drift github action
4
star
46

metaproxy

A proxy that inserts and extracts metadata to/from webpages
Python
4
star
47

django-socketio-example

Django (1.4) + gevent + gevent-socketio + socketio (0.9.x) example
JavaScript
4
star
48

terraform-provider-onepasswordorg

Terraform provider for 1password user and group management
Go
4
star
49

docker-protobuf-py3

Docker protobuf-py3 image
3
star
50

asdf-sloth

Sloth asdf plugin
Shell
3
star
51

kooper-as-dependency

Simple example of a project using kooper and how you could set the dependencies for the project (using dep)
Go
3
star
52

docker-vagrant-gvm

Docker GVM image for vagrant
Shell
3
star
53

docker-mysql

Docker mysql with data only container approach
Shell
3
star
54

sloth-website

https://sloth.dev
HTML
3
star
55

kahoy-app-deploy-example

Production-ready example of application deployments using templating, Kahoy and Kubernetes
Shell
2
star
56

kahoy-kustomize-example

Kahoy and Kustomize with multiple envs (clusters) example
Shell
2
star
57

dwarf

Dwarf is a link shortener made in python and Django, also has statistics and has achievements
Python
2
star
58

mdissphoto

MDISS Master 2011-2012 project
Java
2
star
59

ecs-watcher

ecs-watcher will check periodically your ECS cluster nodes health
Go
2
star
60

daton

Daton
Go
2
star
61

role-operator

Role operator is a kubernetes controller that manages RBAC permissions on namespaces dynamically using roles.
Go
2
star
62

docker-octopress

Octopress container
Shell
2
star
63

ticketbis-dev-box

Ticketbis devel enviroment automation with ansible (Ready for vagrant too)
Shell
1
star
64

submodulo_git

A submodule for the git introduction course
Python
1
star
65

blackbox-helm

Docker image with blackbox and helm
Dockerfile
1
star
66

django-fancymail

Django fancy mail is a layer above django mail that add template rendering easier for the emails. The aim of this project is to be simple, nothing fancy :O.
Python
1
star
67

testing

fdafsasadsadsad
1
star
68

testing_git

1
star
69

docker-postgresql

Docker postgresql container
Shell
1
star
70

warlock

Easy and fast distributed locks for go
Go
1
star
71

custom-css

CSS
1
star
72

go-http-metrics-imports

Example to check the go-http-metrics imports using different frameworks
Go
1
star
73

kahoy-helm-example

A production-ready Kahoy deploy example using Helm as the templating engine
Shell
1
star
74

mydumpster

Mysql dump based on a config file experiment
Go
1
star
75

introduccion_git

Introduction to Git
1
star
76

asdf-agebox

Agebox asdf plugin
Shell
1
star
77

xlarrakoetxeaorg

My future blog made in Flask
Python
1
star
78

ec2-opener

Small util to open a ports on an EC2 instance rapidly.
Go
1
star
79

slackbuilds

My personal slackbuilds
1
star
80

tetris-revivalpp

Tetris clone for the university (2007-2008)
C++
1
star
81

ladder

The new and easy way to autoscale
Go
1
star
82

favorshare-dockerfiles

Shell
1
star
83

python-challenge

Python challenge level scripts
Python
1
star
84

CASO

Project for subject CASO of the 5ΒΊ Curse of Computer engineering in Deusto University
C++
1
star
85

django-chat

Django chat made with Socketio, Gevent[-socketio] and Redis
Python
1
star
86

markdownex

Django web (demo) that renders Markdown sintax
Python
1
star
87

monf

Go
1
star
88

service-level-operator-sloth-migrator

Simple script to migrate CRs from service-level-operator to sloth
Go
1
star
89

docker-make-kubectl

Docker image with make, bash and kubectl
Makefile
1
star