From 419f351df353d29697a940e748c260defb8c7751 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Mon, 5 Dec 2022 13:21:27 -0800 Subject: [PATCH] avoid logging gzipped body in trace output (#16172) --- internal/http/request-recorder.go | 4 ++-- internal/http/response-recorder.go | 18 +++++++++++++----- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/internal/http/request-recorder.go b/internal/http/request-recorder.go index c098624a5..0a1a8b62e 100644 --- a/internal/http/request-recorder.go +++ b/internal/http/request-recorder.go @@ -67,6 +67,6 @@ func (r *RequestRecorder) Data() []byte { if r.LogBody { return r.buf.Bytes() } - // ... otherwise we return placeholder - return BodyPlaceHolder + // ... otherwise we return placeholder + return blobBody } diff --git a/internal/http/response-recorder.go b/internal/http/response-recorder.go index c90f86828..0f4b29d94 100644 --- a/internal/http/response-recorder.go +++ b/internal/http/response-recorder.go @@ -69,7 +69,8 @@ func (lrw *ResponseRecorder) Write(p []byte) (int, error) { if lrw.TimeToFirstByte == 0 { lrw.TimeToFirstByte = time.Now().UTC().Sub(lrw.StartTime) } - if (lrw.LogErrBody && lrw.StatusCode >= http.StatusBadRequest) || lrw.LogAllBody { + gzipped := lrw.Header().Get("Content-Encoding") == "gzip" + if !gzipped && ((lrw.LogErrBody && lrw.StatusCode >= http.StatusBadRequest) || lrw.LogAllBody) { // Always logging error responses. lrw.body.Write(p) } @@ -89,18 +90,25 @@ func (lrw *ResponseRecorder) writeHeaders(w io.Writer, statusCode int, headers h } } -// BodyPlaceHolder returns a dummy body placeholder -var BodyPlaceHolder = []byte("") +// blobBody returns a dummy body placeholder for blob (binary stream) +var blobBody = []byte("") + +// gzippedBody returns a dummy body placeholder for gzipped content +var gzippedBody = []byte("") // Body - Return response body. func (lrw *ResponseRecorder) Body() []byte { + if lrw.Header().Get("Content-Encoding") == "gzip" { + // ... otherwise we return the place holder + return gzippedBody + } // If there was an error response or body logging is enabled // then we return the body contents if (lrw.LogErrBody && lrw.StatusCode >= http.StatusBadRequest) || lrw.LogAllBody { return lrw.body.Bytes() } - // ... otherwise we return the place holder - return BodyPlaceHolder + // ... otherwise we return the place holder + return blobBody } // WriteHeader - writes http status code