prometheus_utils

package module
v0.0.0-...-9177ea0 Latest Latest
Warning

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

Go to latest
Published: Dec 8, 2023 License: Apache-2.0 Imports: 9 Imported by: 0

README

prometheus-utils

Description

The useful library that makes working with Prometheus as easy as possible.

Installation

Run the following command to install the package:

go get github.com/minipkg/prometheus-utils

Basic Usage

Metrics for a http server
with router "github.com/fasthttp/router"
// create httpServerMetric object
metrics := prometheus_utils.NewHttpServerMetrics("chudo-app")

// set handler for Prometheus
r.GET("/metrics", prometheus_utils.GetFasthttpHandler())

// set the middleware for metrics for http handlers
r = metrics.FasthttpRouterMetricsMiddleware(r.Handler))
Example
import (
    "context"
    "fmt"
    "github.com/pkg/errors"
    "net/http"
    "time"

    "github.com/fasthttp/router"
    prometheus_utils "github.com/minipkg/prometheus-utils"
    "github.com/satori/go.uuid"
    "github.com/valyala/fasthttp"
)

func main() {
    metrics := prometheus_utils.NewHttpServerMetrics("chudo-app")
    
    server := &fasthttp.Server{}
    
    r := router.New()
    
    r.GET("/live", LiveHandler)
    r.GET("/ready", LiveHandler)
    r.GET("/metrics", prometheus_utils.GetFasthttpHandler())
    r.GET("/api/v1/test", TestHandler)      //  handler is just for example

    r = RecoverInterceptorMiddleware(RequestIdInterceptorMiddleware(metrics.FasthttpRouterMetricsMiddleware(r.Handler)))
    
    server.Handler = r
        
    server.ListenAndServe(config.Addr)           //  address from config  is just for example
}

func RecoverInterceptorMiddleware(next fasthttp.RequestHandler) fasthttp.RequestHandler {
	return func(rctx *fasthttp.RequestCtx) {
		defer func() {
			if r := recover(); r != nil {
				wblogger.Error(rctx, "PanicInterceptor", fmt.Errorf("%v", r))
				fasthttp_tools.InternalError(rctx, errors.Errorf("%v", r))
			}
		}()
		next(rctx)
	}
}

func RequestIdInterceptorMiddleware(next fasthttp.RequestHandler) fasthttp.RequestHandler {
	return func(rctx *fasthttp.RequestCtx) {
		if requestId := rctx.UserValue(RequestIdKey); requestId == nil {
			if requestIdB := rctx.Request.Header.Peek(RequestIdKey); requestIdB != nil {
				rctx.SetUserValue(RequestIdKey, string(requestIdB))
			} else {
				rctx.SetUserValue(RequestIdKey, uuid.NewV4().String())
			}
		}
		next(rctx)

		return
	}
}

func LiveHandler(rctx *fasthttp.RequestCtx) {
	rctx.SetStatusCode(http.StatusNoContent)
	return
}

with router "github.com/qiangxue/fasthttp-routing"
// create httpServerMetric object
metrics := prometheus_utils.NewHttpServerMetrics("chudo-app")

// set handler for Prometheus
r.Get("/metrics", prometheus_utils.GetFasthttpRoutingHandler())

// set the middleware for metrics for http handlers
r.Use(metrics.FasthttpRoutingMetricsMiddleware)
Example
import (
    "context"
    "fmt"
    "github.com/pkg/errors"
    "net/http"
    "time"

    prometheus_utils "github.com/minipkg/prometheus-utils"
    routing "github.com/qiangxue/fasthttp-routing"
    "github.com/satori/go.uuid"
    "github.com/valyala/fasthttp"
)

func main() {
	metrics := prometheus_utils.NewHttpServerMetrics("chudo-app")

	server := &fasthttp.Server{}

	r := routing.New()

	r.Use(RecoverInterceptorMiddleware, RequestIdInterceptorMiddleware)
	r.Get("/live", LiveHandler)
	r.Get("/ready", LiveHandler)
	r.Get("/metrics", prometheus_utils.GetFasthttpRoutingHandler())
	api := r.Group("/api/v1")
	api.Use(metrics.FasthttpRoutingMetricsMiddleware)
	api.Get("/test", TestHandler)      //  handler is just for example
	server.Handler = r.HandleRequest

	server.ListenAndServe(config.Addr)             //  address from config  is just for example
}

func RecoverInterceptorMiddleware(rctx *routing.Context) error {
	defer func() {
		if r := recover(); r != nil {
			wblogger.Error(rctx, "PanicInterceptor", fmt.Errorf("%v", r))
			fasthttp_tools.InternalError(rctx.RequestCtx, errors.Errorf("%v", r))
		}
	}()
	rctx.Next()
	return nil
}

func RequestIdInterceptorMiddleware(rctx *routing.Context) error {
	if requestId := rctx.Get(RequestIdKey); requestId != nil {
		return nil
	}
	if requestIdB := rctx.RequestCtx.Request.Header.Peek(RequestIdKey); requestIdB != nil {
		rctx.Set(RequestIdKey, string(requestIdB))
		return nil
	}
	rctx.Set(RequestIdKey, uuid.NewV4().String())
    rctx.Next()
	return nil
}

func LiveHandler(rctx *routing.Context) error {
	rctx.SetStatusCode(http.StatusNoContent)
	return nil
}

Documentation

Overview

nolint

Index

Constants

View Source
const (
	AuthClientKey = "http.client"
)

Variables

This section is empty.

Functions

func GetFasthttpHandler

func GetFasthttpHandler() fasthttp.RequestHandler

Handler with metrics for "github.com/fasthttp/router"

func GetFasthttpRoutingHandler

func GetFasthttpRoutingHandler() routing.Handler

Handler with metrics for "github.com/qiangxue/fasthttp-routing"

func MillisecondsFromStart

func MillisecondsFromStart(start time.Time) float64

func NewCounter

func NewCounter(namespace, subsystem, service, counterName, subject string, labels ...string) *counter

NewCounter creates a new named counter for the app labels represent the actions which will be counted

func NewDBGauge

func NewDBGauge(namespace, subsystem, service, host, dbName string) *dbGauge

func NewDbMetrics

func NewDbMetrics(namespace, subsystem, service, host, dbName string) *dbMetrics

func NewGauge

func NewGauge(namespace, subsystem, service, gaugeName, subject string, labels ...string) *gauge

func NewHttpClientMetrics

func NewHttpClientMetrics(namespace, subsystem, service, remoteService string, isNeedToRemoveQueryInPath bool) *httpClientMetric

func NewHttpServerMetrics

func NewHttpServerMetrics(namespace, subsystem, service string, isNeedToRemoveQueryInPath bool) *httpServerMetric

func NewMqMetrics

func NewMqMetrics(appName, host, subject string) *mqMetrics

func NewRedisMetrics

func NewRedisMetrics(namespace, subsystem, service, host string) *redisMetrics

func NewSqlMetrics

func NewSqlMetrics(namespace, subsystem, service, host, dbName string) *sqlMetrics

func NewWorkerMetrics

func NewWorkerMetrics(appName, workerName string) *workerMetrics

NewWorkerMetrics creates a new workerMetrics with the given app and worker name The only label is 'status' i.e. called/failed

func SecondsFromStart

func SecondsFromStart(start time.Time) float64

Types

type DbMetrics

type DbMetrics interface {
	ReadStatsFromDB(s *sql.DB)
}

type Gauge

type Gauge interface {
	Add(valueName string, value float64)
	Set(valueName string, value float64)
}

type HttpClientMetric

type HttpClientMetric interface {
	Inc(method, code, path string)
	WriteTiming(startTime time.Time, method, code, path string)
}

type HttpServerMetric

type HttpServerMetric interface {
	Inc(method, code, path, client string)
	WriteTiming(startTime time.Time, method, code, path, client string)
}

type RedisMetrics

type RedisMetrics interface {
	Inc(query, success string)
	WriteTiming(startTime time.Time, query, success string)
}

type SqlMetrics

type SqlMetrics interface {
	Inc(query, success string)
	WriteTiming(start time.Time, query, success string)
}

Jump to

Keyboard shortcuts

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