From 7234628428ea84bc83a58abca34d0be9aa055822 Mon Sep 17 00:00:00 2001 From: Andre Medeiros Date: Sat, 25 Jun 2022 14:12:56 -0400 Subject: [PATCH] add statsd to API responses --- internal/api/api.go | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/internal/api/api.go b/internal/api/api.go index fdbac49..666f990 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -165,10 +165,12 @@ func (a *api) loggingMiddleware(next http.Handler) http.Handler { start := time.Now() lrw := &LoggingResponseWriter{w: w} - // Do stuff here + // Call the next handler, which can be another middleware in the chain, or the final handler. next.ServeHTTP(lrw, r) + duration := time.Since(start).Milliseconds() + remoteAddr := r.Header.Get("X-Forwarded-For") if remoteAddr == "" { if ip, _, err := net.SplitHostPort(r.RemoteAddr); err != nil { @@ -179,7 +181,7 @@ func (a *api) loggingMiddleware(next http.Handler) http.Handler { } fields := []zap.Field{ - zap.Int64("duration", time.Since(start).Milliseconds()), + zap.Int64("duration", duration), zap.String("method", r.Method), zap.String("remote#addr", remoteAddr), zap.Int("response#bytes", lrw.bytes), @@ -193,5 +195,12 @@ func (a *api) loggingMiddleware(next http.Handler) http.Handler { err := lrw.Header().Get("X-Apollo-Error") a.logger.Error(err, fields...) } + + tags := []string{fmt.Sprintf("status:%d", lrw.statusCode)} + _ = a.statsd.Histogram("api.latency", float64(duration), tags, 0.1) + _ = a.statsd.Incr("api.calls", nil, 0.1) + if lrw.statusCode >= 500 { + _ = a.statsd.Incr("api.errors", nil, 0.1) + } }) }