• Stars
    star
    122
  • Rank 292,031 (Top 6 %)
  • Language
    Go
  • License
    MIT License
  • Created about 7 years ago
  • Updated over 1 year ago

Reviews

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

Repository Details

Gin Prometheus metrics exporter

Ginprom

Gin Prometheus metrics exporter

Sourcegraph Go Report Card Build Status codecov License godoc

Inspired by github.com/zsais/go-gin-prometheus

Install

Simply run: go get -u github.com/Depado/ginprom

Differences with go-gin-prometheus

  • No support for Prometheus' Push Gateway
  • Options on constructor
  • Adds a path label to get the matched route
  • Ability to ignore routes

Usage

package main

import (
	"github.com/Depado/ginprom"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	p := ginprom.New(
		ginprom.Engine(r),
		ginprom.Subsystem("gin"),
		ginprom.Path("/metrics"),
	)
	r.Use(p.Instrument())

	r.GET("/hello/:id", func(c *gin.Context) {})
	r.GET("/world/:id", func(c *gin.Context) {})
	r.Run("127.0.0.1:8080")
}

Options

Custom Counters

Add custom counters to add own values to the metrics

r := gin.New()
p := ginprom.New(
	ginprom.Engine(r),
)
p.AddCustomCounter("custom", "Some help text to provide", []string{"label"})
r.Use(p.Instrument())

Save p and use the following functions:

  • IncrementCounterValue
  • AddCounterValue

Custom gauges

Add custom gauges to add own values to the metrics

r := gin.New()
p := ginprom.New(
	ginprom.Engine(r),
)
p.AddCustomGauge("custom", "Some help text to provide", []string{"label"})
r.Use(p.Instrument())

Save p and use the following functions:

  • IncrementGaugeValue
  • DecrementGaugeValue
  • SetGaugeValue

Path

Override the default path (/metrics) on which the metrics can be accessed:

r := gin.New()
p := ginprom.New(
	ginprom.Engine(r),
	ginprom.Path("/custom/metrics"),
)
r.Use(p.Instrument())

Namespace

Override the default namespace (gin):

r := gin.New()
p := ginprom.New(
	ginprom.Engine(r),
	ginprom.Namespace("custom_ns"),
)
r.Use(p.Instrument())

Subsystem

Override the default (gonic) subsystem:

r := gin.New()
p := ginprom.New(
	ginprom.Engine(r),
	ginprom.Subsystem("your_subsystem"),
)
r.Use(p.Instrument())

Engine

The preferred way to pass the router to ginprom:

r := gin.New()
p := ginprom.New(
	ginprom.Engine(r),
)
r.Use(p.Instrument())

The alternative being to call the Use method after initialization:

p := ginprom.New()
// ...
r := gin.New()
p.Use(r)
r.Use(p.Instrument())

Prometheus Registry

Use a custom prometheus.Registry instead of prometheus client's global registry. This option allows to use ginprom in multiple gin engines in the same process, or if you would like to integrate ginprom with your own prometheus Registry.

registry := prometheus.NewRegistry() // creates new prometheus metric registry
r := gin.New()
p := ginprom.New(
    ginprom.Registry(registry),
)
r.Use(p.Instrument())

HandlerNameFunc

Change the way the handler label is computed. By default, the (*gin.Context).HandlerName function is used. This option is useful when wanting to group different functions under the same handler label or when using gin with decorated handlers.

r := gin.Default()
p := ginprom.New(
	HandlerNameFunc(func (c *gin.Context) string {
		return "my handler"
	}),
)
r.Use(p.Instrument())

RequestPathFunc

Change how the path label is computed. By default, the (*gin.Context).FullPath function is used. This option is useful when wanting to group different requests under the same path label or when wanting to process unknown routes (the default (*gin.Context).FullPath returns an empty string for unregistered routes). Note that requests for which f returns the empty string are ignored.

To specifically ignore certain paths, see the Ignore option.

r := gin.Default()
p := ginprom.New(
	// record a metric for unregistered routes under the path label "<unknown>"
	RequestPathFunc(func (c *gin.Context) string {
		if fullpath := c.FullPath(); fullpath != "" {
			return fullpath
		}
		return "<unknown>"
	}),
)
r.Use(p.Instrument())

Ignore

Ignore allows to completely ignore some routes. Even though you can apply the middleware to the only groups you're interested in, it is sometimes useful to have routes not instrumented.

r := gin.New()
p := ginprom.New(
	ginprom.Engine(r),
	ginprom.Ignore("/api/no/no/no", "/api/super/secret/route")
)
r.Use(p.Instrument())

Note that most of the time this can be solved by gin groups:

r := gin.New()
p := ginprom.New(ginprom.Engine(r))

// Add the routes that do not need instrumentation
g := r.Group("/api/")
g.Use(p.Instrument())
{
	// Instrumented routes
}

Token

Specify a secret token which Prometheus will use to access the endpoint. If the token is invalid, the endpoint will return an error.

r := gin.New()
p := ginprom.New(
	ginprom.Engine(r),
	ginprom.Token("supersecrettoken")
)
r.Use(p.Instrument())

Bucket size

Specify the bucket size for the request duration histogram according to your expected durations.

r := gin.New()
p := ginprom.New(
	ginprom.Engine(r),
	ginprom.BucketSize([]float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10}),
)
r.Use(p.Instrument())

Troubleshooting

The instrumentation doesn't seem to work

Make sure you have set the gin.Engine in the ginprom middleware, either when initializing it using ginprom.New(ginprom.Engine(r)) or using the Use function after the initialization like this :

p := ginprom.New(
	ginprom.Namespace("gin"),
	ginprom.Subsystem("gonic"),
	ginprom.Path("/metrics"),
)
p.Use(r)
r.Use(p.Instrument())

By design, if the middleware was to panic, it would do so when a route is called. That's why it just silently fails when no engine has been set.

More Repositories

1

goploader

Easy file sharing with server-side encryption, curl/httpie/wget compliant
JavaScript
260
star
2

gin-auth-example

An attempt at authentication with Gin
Go
123
star
3

bfchroma

Integrating Chroma syntax highlighter as a Blackfriday renderer
Go
62
star
4

flask-skeleton

A simple script to create a flask application using command line.
Python
47
star
5

articles

Articles hosted on my blog
Go
30
star
6

smallblog

Flat file markdown blogging system with filesystem watch and extended markdown support
Go
27
star
7

quokka

Project boilerplate engine
Go
26
star
8

MarkDownBlog

A flask web application that allows to create blog. Creates automatically a subdomain with the nickname of the user.
CSS
23
star
9

parakeet

A SoundCloud player in your terminal
Go
16
star
10

platypus

Very simple and customizable mock/echo server
Go
14
star
11

chromarkdown

Generate single-file static responsive HTML page from Markdown with syntax-highlighting.
Go
13
star
12

govue

An attempt to work with Vue.js and a golang gin rest server
Go
10
star
13

gomonit

Small soft to check if your services are running, providing a web interface.
CSS
8
star
14

LostInNetwork

A web application to manage and detect security flaws on devices on a network.
Python
6
star
15

go-b0tsec

A pretty simple IRC Bot with plugins and middlewares.
Go
5
star
16

gopaste

Self-hosted pastebin written in Go
HTML
5
star
17

vuemonit

Rework on gomonit app
Go
4
star
18

Kimsuchecker

Check for available offers on Kimsufi
Go
4
star
19

termui-testing

A simple test displaying CPU and Memory usage with dynamic bars and charts
Go
4
star
20

markov-bot

An irc bot that builds markov chains using log files and generate random sentences when called.
Go
3
star
21

jagon-api

A simple automated religion API
HTML
3
star
22

memegen

Simple meme generator
Go
3
star
23

fox

Discord bot playing your Soundcloud musics and playlists in a voice channel
Go
3
star
24

go-gh-stats

Playing with the GitHub API to retrieve some statistics
Go
2
star
25

gofip

A FIP Webradio player that also displays the previous/current/next songs
Go
2
star
26

yasrpg

Yet Another SNES RPG
Python
2
star
27

simple-go-file-server

A simple go program to serve files.
Go
2
star
28

we-rate

A flask application for rating stuff like movies, series, videogames.
Python
2
star
29

go-examples

A bunch of Go snippets that I use often and forget frequently.
Go
2
star
30

qktemplates

Repository that holds some Quokka templates
Go
2
star
31

soundcloud

A work in progress golang client for SoundCloud v2
Go
2
star
32

bfplus

Blackfriday Renderer that supports admonitions, auto-heading links and code highlighting using Chroma
Go
2
star
33

periodic-file-fetcher

A simple go program used to fetch a distant resource and backup its changes periodically
Go
2
star
34

mars-project

A modelisation of the Mars planet using MonoGame
C#
2
star
35

rpsheet

Experiment with MDL and tabletop RPG data
Go
1
star
36

assistant-codelabs

Code for the backend of the Google Assistant codelab
Go
1
star
37

quotescrapper

A poorly made french quote scrapper
Go
1
star
38

test-go-sdl2

Trying to use the go-sdl2 library.
Go
1
star
39

golri

One of the best Go project you could think of.
1
star
40

launeparser

Parsing newspapers everyday to get a corpus
Go
1
star
41

cuites.stream

Vue
1
star
42

experiments

Repo for website
JavaScript
1
star
43

goji-webapp

A simple web application based on the excellent elcct's defaultproject
Go
1
star
44

ish

Ingesup Shell written in C
C
1
star
45

opensirene-ui

Frontend for easy data access using opensirene API
Go
1
star
46

UnicornChat

A simple websocket based chat with a node.js server.
JavaScript
1
star
47

LostInNetworkWeb

Website for LostInNetwork (LiN) project
CSS
1
star
48

gamechooser

Simple game launcher written in Gtk with Gobject Introspection (Pygobject)
Python
1
star
49

thundermonit

[WIP] Rework of gomonit to use graphql, clean design architecture and overall better code style
Go
1
star
50

mdblog-curses-reader

An ncurses based program to read article directly in your 256-color terminal.
Go
1
star
51

CAT

The Conversational Agent Thinking
Python
1
star
52

intrepid-frontend

Frontend for the IntrePid distribution.
Python
1
star
53

b0tsec

A python IRC Bot which does random things.
Python
1
star
54

go-testing

A set of small programs to test the go language, concurrency and libraries
Go
1
star
55

starmato-admin

Advanced features for the Django admin
Python
1
star
56

dtc-cli

Get quotes from DTC and display them in your terminal
Python
1
star