mirror of
https://github.com/fnproject/fn.git
synced 2022-10-28 21:29:17 +03:00
Api metrics (#1014)
* api metrics support * comments reflected * metrics middleware fix
This commit is contained in:
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user