Skip to content

Instantly share code, notes, and snippets.

@rkhmelyuk
Last active February 18, 2018 02:51
Show Gist options
  • Save rkhmelyuk/d8aa6f7b7d687f4d340d90d13c818b09 to your computer and use it in GitHub Desktop.
Save rkhmelyuk/d8aa6f7b7d687f4d340d90d13c818b09 to your computer and use it in GitHub Desktop.
Metrics handler for Gin
// 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