Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module github.com/carousell/fasthttp-prometheus-middleware
go 1.13

require (
github.com/fasthttp/router v0.5.2
github.com/fasthttp/router v1.3.2
github.com/prometheus/client_golang v1.2.1
github.com/valyala/fasthttp v1.6.0
)
16 changes: 13 additions & 3 deletions prometheus.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package fasthttpprom

import (
"fmt"
"strconv"
"time"

Expand All @@ -23,6 +24,7 @@ type Prometheus struct {
listenAddress string
MetricsPath string
Handler fasthttp.RequestHandler
groupPath bool
}

// NewPrometheus generates a new set of metrics with a certain subsystem name
Expand All @@ -35,6 +37,10 @@ func NewPrometheus(subsystem string) *Prometheus {
return p
}

func (p *Prometheus) SetPathGrouping(enabled bool) {
p.groupPath = enabled
}

// SetListenAddress for exposing metrics on address. If not set, it will be exposed at the
// same address of api that is being used
func (p *Prometheus) SetListenAddress(address string) {
Expand Down Expand Up @@ -77,7 +83,7 @@ func (p *Prometheus) registerMetrics(subsystem string) {
Help: "request latencies",
Buckets: []float64{.005, .01, .02, 0.04, .06, 0.08, .1, 0.15, .25, 0.4, .6, .8, 1, 1.5, 2, 3, 5},
},
[]string{"code", "path"},
[]string{"code", "path", "method"},
)

prometheus.Register(p.reqDur)
Expand Down Expand Up @@ -113,8 +119,12 @@ func (p *Prometheus) HandlerFunc() fasthttp.RequestHandler {

status := strconv.Itoa(ctx.Response.StatusCode())
elapsed := float64(time.Since(start)) / float64(time.Second)
ep := string(ctx.Method()) + "_" + uri
p.reqDur.WithLabelValues(status, ep).Observe(elapsed)
if p.groupPath == true {
uri = fmt.Sprintf("%v", ctx.UserValue(router.MatchedRoutePathParam))
}
ep := uri
method := string(ctx.Method())
p.reqDur.WithLabelValues(status, ep, method).Observe(elapsed)
}
}

Expand Down