Api metrics (#1014)

* api metrics support

* comments reflected

* metrics middleware fix
This commit is contained in:
Tomas Knappek
2018-05-25 08:31:37 -07:00
committed by Shiva
parent 05caef0d26
commit e3e264de53
3 changed files with 121 additions and 0 deletions

View File

@@ -14,8 +14,11 @@ import (
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"go.opencensus.io/stats"
"go.opencensus.io/tag"
"go.opencensus.io/trace"
"strconv"
"time"
)
func optionalCorsWrap(r *gin.Engine) {
@@ -75,6 +78,54 @@ func traceWrap(c *gin.Context) {
c.Next()
}
func apiMetricsWrap(s *Server) {
measure := func(engine *gin.Engine) func(*gin.Context) {
var routes gin.RoutesInfo
return func(c *gin.Context) {
if routes == nil {
routes = engine.Routes()
}
start := time.Now()
// get the handler url, example: /v1/apps/:app
url := ""
for _, r := range routes {
if r.Handler == c.HandlerName() {
url = r.Path
break
}
}
ctx, err := tag.New(c.Request.Context(),
tag.Upsert(pathKey, url),
tag.Upsert(methodKey, c.Request.Method),
)
if err != nil {
logrus.Fatal(err)
}
stats.Record(ctx, apiRequestCount.M(1))
c.Next()
status := strconv.Itoa(c.Writer.Status())
ctx, err = tag.New(ctx,
tag.Upsert(statusKey, status),
)
if err != nil {
logrus.Fatal(err)
}
stats.Record(ctx, apiLatency.M(float64(time.Since(start))/float64(time.Millisecond)))
}
}
r := s.Router
r.Use(measure(r))
if s.webListenPort != s.adminListenPort {
a := s.AdminRouter
a.Use(measure(a))
}
}
func panicWrap(c *gin.Context) {
defer func(c *gin.Context) {
if rec := recover(); rec != nil {