prome

package
v0.0.12 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 3, 2021 License: MIT Imports: 10 Imported by: 0

README

prome

Prometheus Client for easy use.

Why

I wrote this library so i can easily use it in my Go projects.

Features

  • Easy easy.
  • Provide basic Go runtime metrics.
  • Support gin middleware for providing API request counts and duration metrics.
  • Easy for developer to add custom metrics.

Usage

The simplest usage:

func main() {
	client := prome.NewClient("test", "/foo")
	if err := client.ListenAndServe(":9000"); err != nil {
		panic(err)
	}
}

Just include the code above already provides you the Go runtime metrics info. You can run curl "http://127.0.0.1:9000/foo" and get the prometheus data.

11:57 tmp ➜  curl "http://127.0.0.1:9000/foo"
# HELP test_runtime_gomaxprocs Runtime GOMAXPROCS
# TYPE test_runtime_gomaxprocs gauge
test_runtime_gomaxprocs 4
# HELP test_runtime_memstats_alloc Runtime memstats alloc (Unit: byte)
# TYPE test_runtime_memstats_alloc gauge
test_runtime_memstats_alloc 1.346416e+06
# HELP test_runtime_memstats_last_gc Runtime memstats last GC pause (Unit: ns)
# TYPE test_runtime_memstats_last_gc gauge
test_runtime_memstats_last_gc 0
# HELP test_runtime_memstats_sys Runtime memstats sys (Unit: byte)
# TYPE test_runtime_memstats_sys gauge
test_runtime_memstats_sys 7.2827136e+07
# HELP test_runtime_num_cpu Runtime number of CPUs
# TYPE test_runtime_num_cpu gauge
test_runtime_num_cpu 4
# HELP test_runtime_num_goroutine Runtime number of goroutines
# TYPE test_runtime_num_goroutine gauge
test_runtime_num_goroutine 3
# HELP test_runtime_os_threads Runtime number of OS threads
# TYPE test_runtime_os_threads gauge
test_runtime_os_threads 7

Examples

You can get more examples in the examples directory to find more advenced usage.

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultRequestDurationSummaryObjectives = map[float64]float64{
	0.5:  0.05,
	0.9:  0.01,
	0.95: 0.005,
	0.99: 0.001,
}

DefaultRequestDurationSummaryObjectives represents objectives of request duration middleware summary.

Functions

This section is empty.

Types

type Client

type Client struct {
	ServiceName string
	Path        string

	// Enable metrics of runtime. Default enabled.
	EnableRuntime bool
	// Interval of update memstats. Unit: seconds. Default 60s.
	UpdateMemStatsInterval int

	// Labels which will always be attached to metrics.
	ConstLabels prometheus.Labels
	// contains filtered or unexported fields
}

Client represents the client for prometheus server to pull data from.

Example (Basic1)
package main

import (
	"github.com/alfred-zhong/goutil/prome"
)

func main() {
	client := prome.NewClientWithOption("test", "/foo")
	if err := client.ListenAndServe(":9000"); err != nil {
		panic(err)
	}
}
Output:

Example (Basic2)
package main

import (
	"github.com/alfred-zhong/goutil/prome"
)

func main() {
	client := prome.NewClientWithOption(
		"test", "/foo",
		prome.WithRuntimeEnable(true, 5),
	)
	if err := client.ListenAndServe(":9000"); err != nil {
		panic(err)
	}
}
Output:

Example (Custommetrics)
package main

import (
	"math/rand"
	"time"

	"github.com/alfred-zhong/goutil/prome"
	"github.com/prometheus/client_golang/prometheus"
)

func main() {
	client := prome.NewClientWithOption(
		"test", "/foo",
		prome.WithRuntimeEnable(false, 0),
	)
	client.ConstLabels = prometheus.Labels{
		"env": "test",
	}

	counter := client.AddCounter(prometheus.CounterOpts{
		Name: "test_counter",
	})
	counterVec := client.AddCounterVec(prometheus.CounterOpts{
		Name: "test_counterVec",
	}, []string{"name"})

	gauge := client.AddGauge(prometheus.GaugeOpts{
		Name: "test_gauge",
	})
	gaugeVec := client.AddGaugeVec(prometheus.GaugeOpts{
		Name: "test_gaugeVec",
	}, []string{"name"})

	histogram := client.AddHistogram(prometheus.HistogramOpts{
		Name:    "test_histogram",
		Buckets: []float64{10, 20, 30, 40, 50},
	})
	histogramVec := client.AddHistogramVec(prometheus.HistogramOpts{
		Name:    "test_histogramVec",
		Buckets: []float64{10, 20, 30, 40, 50},
	}, []string{"name"})

	summary := client.AddSummary(prometheus.SummaryOpts{
		Name:       "test_summary",
		Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
	})
	summaryVec := client.AddSummaryVec(prometheus.SummaryOpts{
		Name:       "test_summaryVec",
		Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
	}, []string{"name"})

	go func() {
		for {
			counter.Inc()
			counterVec.WithLabelValues("hysteria").Inc()

			gauge.Inc()
			gaugeVec.WithLabelValues("roxanne").Inc()

			histogram.Observe(rand.Float64() * 100)
			histogramVec.WithLabelValues("cassandra").Observe(rand.Float64() * 100)

			summary.Observe(rand.Float64() * 100)
			summaryVec.WithLabelValues("hysteria").Observe(rand.Float64() * 30)
			summaryVec.WithLabelValues("roxanne").Observe(rand.Float64() * 50)
			summaryVec.WithLabelValues("riful").Observe(rand.Float64() * 100)

			time.Sleep(time.Second)
		}
	}()

	if err := client.ListenAndServe(":9000"); err != nil {
		panic(err)
	}
}
Output:

Example (Gin)
package main

import (
	"math/rand"
	"time"

	"github.com/alfred-zhong/goutil/prome"
	"github.com/gin-gonic/gin"
)

func main() {
	client := prome.NewClientWithOption(
		"test", "",
		prome.WithRuntimeEnable(false, 0),
	)

	e := gin.New()
	e.Use(client.MiddlewareRequestCount(""))
	e.Use(client.MiddlewareRequestDuration("", nil))

	e.GET("/foo", gin.WrapH(client.Handler()))
	e.GET("/hello/:name", func(c *gin.Context) {
		c.String(200, "indeed, %s", c.Param("name"))
	})
	e.GET("/sleep", func(c *gin.Context) {
		time.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)
	})
	if err := e.Run(":9527"); err != nil {
		panic(err)
	}
}
Output:

Example (Labels)
package main

import (
	"github.com/alfred-zhong/goutil/prome"
)

func main() {
	client := prome.NewClientWithOption(
		"test", "/foo",
		prome.WithConstLables(
			"env", "test",
			"foo", "bar",
		),
	)
	if err := client.ListenAndServe(":9000"); err != nil {
		panic(err)
	}
}
Output:

Example (Shutdown)
package main

import (
	"fmt"
	"time"

	"github.com/alfred-zhong/goutil/prome"
)

func main() {
	client := prome.NewClientWithOption("test", "/foo")
	go func() {
		if err := client.ListenAndServe(":9000"); err != nil {
			panic(err)
		}
		fmt.Println("server shutdown")
	}()

	time.Sleep(5 * time.Second)
	if err := client.Close(); err != nil {
		panic(err)
	}
	time.Sleep(10 * time.Second)
}
Output:

Example (Withoutruntime)
package main

import (
	"github.com/alfred-zhong/goutil/prome"
)

func main() {
	client := prome.NewClientWithOption(
		"test", "/foo",
		prome.WithRuntimeEnable(false, 0),
	)
	if err := client.ListenAndServe(":9000"); err != nil {
		panic(err)
	}
}
Output:

func NewClient deprecated

func NewClient(serviceName string, path string) *Client

NewClient creates and returns a new Client instance.

Deprecated: Use NewClientWithOption instead.

func NewClientWithOption added in v0.0.7

func NewClientWithOption(serviceName, path string, opts ...Option) *Client

NewClientWithOption creates Client with optional Option.

func (*Client) AddCounter

func (c *Client) AddCounter(opts prometheus.CounterOpts) prometheus.Counter

AddCounter creates a new Counter based on the provided CounterOpts which will be registered automatically when client serves.

func (*Client) AddCounterVec

func (c *Client) AddCounterVec(
	opts prometheus.CounterOpts, labelNames []string,
) *prometheus.CounterVec

AddCounterVec creates a new CounterVec based on the provided CounterOpts and partitioned by the given label names which will be registered automatically when client serves.

func (*Client) AddGauge

func (c *Client) AddGauge(opts prometheus.GaugeOpts) prometheus.Gauge

AddGauge creates a new Gauge based on the provided GaugeOpts which will be registered automatically when client serves.

func (*Client) AddGaugeVec

func (c *Client) AddGaugeVec(
	opts prometheus.GaugeOpts, labelNames []string,
) *prometheus.GaugeVec

AddGaugeVec creates a new GaugeVec based on the provided GaugeOpts and partitioned by the given label names which will be registered automatically when client serves.

func (*Client) AddHistogram

func (c *Client) AddHistogram(opts prometheus.HistogramOpts) prometheus.Histogram

AddHistogram creates a new Histogram based on the provided HistogramOpts which will be registered automatically when client serves.

func (*Client) AddHistogramVec

func (c *Client) AddHistogramVec(
	opts prometheus.HistogramOpts, labelNames []string,
) *prometheus.HistogramVec

AddHistogramVec creates a new HistogramVec based on the provided HistogramOpts and partitioned by the given label names which will be registered automatically when client serves.

func (*Client) AddSummary

func (c *Client) AddSummary(opts prometheus.SummaryOpts) prometheus.Summary

AddSummary creates a new Summary based on the provided SummaryOpts which will be registered automatically when client serves.

func (*Client) AddSummaryVec

func (c *Client) AddSummaryVec(
	opts prometheus.SummaryOpts, labelNames []string,
) *prometheus.SummaryVec

AddSummaryVec creates a new SummaryVec based on the provided SummaryOpts and partitioned by the given label names which will be registered automatically when client serves.

func (*Client) Close

func (c *Client) Close() error

Close shutdown of listening.

func (*Client) Handler

func (c *Client) Handler() http.Handler

Handler returns the http handler which can be used for fetch metrics data.

func (*Client) ListenAndServe

func (c *Client) ListenAndServe(addr string) error

ListenAndServe listen on the addr and provide access for prometheus server to pull data.

func (*Client) MiddlewareRequestCount

func (c *Client) MiddlewareRequestCount(metricsName string) gin.HandlerFunc

MiddlewareRequestCount returns a gin HandlerFunc which can be used as middleware to capture request count.

func (*Client) MiddlewareRequestDuration

func (c *Client) MiddlewareRequestDuration(
	metricsName string, objectives map[float64]float64,
) gin.HandlerFunc

MiddlewareRequestDuration returns a gin handler which can be used as middleware to capture request duration summary.

type Option added in v0.0.7

type Option func(*Client)

Option defines argument for create Server.

func WithConstLables added in v0.0.7

func WithConstLables(kv ...string) Option

WithConstLables creates Option which append const labels to the client.

func WithRuntimeEnable added in v0.0.7

func WithRuntimeEnable(enable bool, updateMemstatsInterval int) Option

WithRuntimeEnable creates Option which determines whether to enables metrics of runtime. updateMemstatsInterval make sense only if enable set to true.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL