avoid logging gzipped body in trace output (#16172)

This commit is contained in:
Harshavardhana 2022-12-05 13:21:27 -08:00 committed by GitHub
parent 180d6b30ca
commit 419f351df3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 15 additions and 7 deletions

View File

@ -67,6 +67,6 @@ func (r *RequestRecorder) Data() []byte {
if r.LogBody { if r.LogBody {
return r.buf.Bytes() return r.buf.Bytes()
} }
// ... otherwise we return <BODY> placeholder // ... otherwise we return <BLOB> placeholder
return BodyPlaceHolder return blobBody
} }

View File

@ -69,7 +69,8 @@ func (lrw *ResponseRecorder) Write(p []byte) (int, error) {
if lrw.TimeToFirstByte == 0 { if lrw.TimeToFirstByte == 0 {
lrw.TimeToFirstByte = time.Now().UTC().Sub(lrw.StartTime) 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. // Always logging error responses.
lrw.body.Write(p) 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 // blobBody returns a dummy body placeholder for blob (binary stream)
var BodyPlaceHolder = []byte("<BODY>") var blobBody = []byte("<BLOB>")
// gzippedBody returns a dummy body placeholder for gzipped content
var gzippedBody = []byte("<GZIP>")
// Body - Return response body. // Body - Return response body.
func (lrw *ResponseRecorder) Body() []byte { func (lrw *ResponseRecorder) Body() []byte {
if lrw.Header().Get("Content-Encoding") == "gzip" {
// ... otherwise we return the <GZIP> place holder
return gzippedBody
}
// If there was an error response or body logging is enabled // If there was an error response or body logging is enabled
// then we return the body contents // then we return the body contents
if (lrw.LogErrBody && lrw.StatusCode >= http.StatusBadRequest) || lrw.LogAllBody { if (lrw.LogErrBody && lrw.StatusCode >= http.StatusBadRequest) || lrw.LogAllBody {
return lrw.body.Bytes() return lrw.body.Bytes()
} }
// ... otherwise we return the <BODY> place holder // ... otherwise we return the <BLOB> place holder
return BodyPlaceHolder return blobBody
} }
// WriteHeader - writes http status code // WriteHeader - writes http status code