add statsd to API responses

This commit is contained in:
Andre Medeiros 2022-06-25 14:12:56 -04:00
parent f4e5d7e979
commit 7234628428

View file

@ -165,10 +165,12 @@ func (a *api) loggingMiddleware(next http.Handler) http.Handler {
start := time.Now() start := time.Now()
lrw := &LoggingResponseWriter{w: w} lrw := &LoggingResponseWriter{w: w}
// Do stuff here
// Call the next handler, which can be another middleware in the chain, or the final handler. // Call the next handler, which can be another middleware in the chain, or the final handler.
next.ServeHTTP(lrw, r) next.ServeHTTP(lrw, r)
duration := time.Since(start).Milliseconds()
remoteAddr := r.Header.Get("X-Forwarded-For") remoteAddr := r.Header.Get("X-Forwarded-For")
if remoteAddr == "" { if remoteAddr == "" {
if ip, _, err := net.SplitHostPort(r.RemoteAddr); err != nil { 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{ fields := []zap.Field{
zap.Int64("duration", time.Since(start).Milliseconds()), zap.Int64("duration", duration),
zap.String("method", r.Method), zap.String("method", r.Method),
zap.String("remote#addr", remoteAddr), zap.String("remote#addr", remoteAddr),
zap.Int("response#bytes", lrw.bytes), 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") err := lrw.Header().Get("X-Apollo-Error")
a.logger.Error(err, fields...) 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)
}
}) })
} }