Skip to content

Commit

Permalink
fix when to invoke NewPrometheusMiddleware twice lead a panic
Browse files Browse the repository at this point in the history
  • Loading branch information
hanjm committed May 22, 2017
1 parent b8928e0 commit c205591
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions prometheusmiddleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
)

var (
isRegistered = false // fix when to invoke NewPrometheusMiddleware twice lead a panic: duplicate metrics collector registration attempted
promLabelNames = []string{"code", "method", "path"}
requestCounter = prometheus.NewCounterVec(
prometheus.CounterOpts(prometheus.Opts{
Expand All @@ -29,13 +30,16 @@ var (
// The prometheus is a monitoring system and time series database.
// Note: the returned middleware contains the function of logmiddleware.
func NewPrometheusMiddleware(bindAddr string, xRealIp bool, logger *zap.Logger) Middleware {
go func() {
prometheus.MustRegister(requestCounter)
prometheus.MustRegister(responseTimeSummary)
http.Handle("/metrics", promhttp.Handler())
logger.Debug("prometheus metrics server start at " + bindAddr)
http.ListenAndServe(bindAddr, nil)
}()
if !isRegistered {
go func() {
prometheus.MustRegister(requestCounter)
prometheus.MustRegister(responseTimeSummary)
isRegistered = true
http.Handle("/metrics", promhttp.Handler())
logger.Debug("prometheus metrics server start at " + bindAddr)
http.ListenAndServe(bindAddr, nil)
}()
}
return func(h fasthttp.RequestHandler) fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
startTime := time.Now()
Expand All @@ -50,7 +54,7 @@ func NewPrometheusMiddleware(bindAddr string, xRealIp bool, logger *zap.Logger)
responseTime := time.Since(startTime).Seconds() * 1000
responseTimeSummary.With(promLabels).Observe(responseTime)
requestCounter.With(promLabels).Inc()
if ctx.Response.StatusCode()/100 == 2 {
if ctx.Response.StatusCode() / 100 == 2 {
logger.Info("access", zap.Int("code", ctx.Response.StatusCode()), zap.Float64("time", responseTime), zap.String("method", promLabels["method"]), zap.String("path", promLabels["path"]), addrField)
} else {
logger.Warn("access", zap.Int("code", ctx.Response.StatusCode()), zap.Float64("time", responseTime), zap.String("method", promLabels["method"]), zap.String("path", promLabels["path"]), addrField)
Expand Down

0 comments on commit c205591

Please sign in to comment.