Last active
February 18, 2018 02:51
-
-
Save rkhmelyuk/d8aa6f7b7d687f4d340d90d13c818b09 to your computer and use it in GitHub Desktop.
Metrics handler for Gin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Metrics handler collects metrics about registered handlers: | |
// latency, requests count, request and response size etc. | |
func Metrics() gin.HandlerFunc { | |
return func(c *gin.Context) { | |
path := getHandlerName(c) | |
timerMetric := metrics.GetOrRegisterTimer("call."+path+".Latency", nil) | |
start := time.Now() | |
c.Next() | |
timerMetric.UpdateSince(start) | |
metrics.GetOrRegisterGauge("call."+path+".RequestSize", nil).Update(int64(c.Request.ContentLength)) | |
metrics.GetOrRegisterGauge("call."+path+".ResponseSize", nil).Update(int64(c.Writer.Size())) | |
} | |
} | |
// Gets short handler name | |
func getHandlerName(c *gin.Context) string { | |
handlerName := c.HandlerName() | |
path := handlerName | |
lastIndex := strings.LastIndex(handlerName, ".") | |
if lastIndex != -1 { | |
path = handlerName[lastIndex+1:] | |
} | |
return path | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment