Skip to content

Instantly share code, notes, and snippets.

@ru-rocker
Created April 1, 2017 14:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ru-rocker/e443d8a1bdc07b54b7a7abbc868e69e7 to your computer and use it in GitHub Desktop.
Save ru-rocker/e443d8a1bdc07b54b7a7abbc868e69e7 to your computer and use it in GitHub Desktop.
metrics middleware
package lorem_metrics
import (
"github.com/go-kit/kit/metrics"
"time"
)
func Metrics(requestCount metrics.Counter,
requestLatency metrics.Histogram) ServiceMiddleware {
return func(next Service) Service {
return metricsMiddleware{
next,
requestCount,
requestLatency,
}
}
}
// Make a new type and wrap into Service interface
// Add expected metrics property to this type
type metricsMiddleware struct {
Service
requestCount metrics.Counter
requestLatency metrics.Histogram
}
// Implement service functions and add label method for our metrics
func (mw metricsMiddleware) Word(min, max int) (output string) {
defer func(begin time.Time) {
lvs := []string{"method", "Word"}
mw.requestCount.With(lvs...).Add(1)
mw.requestLatency.With(lvs...).Observe(time.Since(begin).Seconds())
}(time.Now())
output = mw.Service.Word(min, max)
return
}
func (mw metricsMiddleware) Sentence(min, max int) (output string) {
defer func(begin time.Time) {
lvs := []string{"method", "Sentence"}
mw.requestCount.With(lvs...).Add(1)
mw.requestLatency.With(lvs...).Observe(time.Since(begin).Seconds())
}(time.Now())
output = mw.Service.Sentence(min, max)
return
}
func (mw metricsMiddleware) Paragraph(min, max int) (output string) {
defer func(begin time.Time) {
lvs := []string{"method", "Paragraph"}
mw.requestCount.With(lvs...).Add(1)
mw.requestLatency.With(lvs...).Observe(time.Since(begin).Seconds())
}(time.Now())
output = mw.Service.Paragraph(min, max)
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment