From cf6d435b6e1e874ac71b5aa504eb834bbb939af7 Mon Sep 17 00:00:00 2001 From: andig Date: Sat, 15 May 2021 11:26:52 +0200 Subject: [PATCH] Improve http request logging --- util/request/roundtrip.go | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/util/request/roundtrip.go b/util/request/roundtrip.go index 6fb16b817..f702d9d60 100644 --- a/util/request/roundtrip.go +++ b/util/request/roundtrip.go @@ -1,6 +1,7 @@ package request import ( + "bytes" "net/http" "net/http/httputil" "strings" @@ -25,26 +26,35 @@ func NewTripper(log *util.Logger, transport http.RoundTripper) http.RoundTripper return tripper } +var bld = strings.Builder{} + +func min(a, b int) int { + if a < b { + return a + } + return b +} + func (r *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - if body, err := httputil.DumpRequest(req, true); err == nil { - s := strings.TrimSpace(string(body)) - if len(s) > max { - s = s[:max] - } - r.log.TRACE.Println(s) + bld.Reset() + + if body, err := httputil.DumpRequestOut(req, true); err == nil { + bld.WriteString("\n") + bld.Write(bytes.TrimSpace(body[:min(max, len(body))])) } resp, err := r.transport.RoundTrip(req) if resp != nil { if body, err := httputil.DumpResponse(resp, true); err == nil { - s := strings.TrimSpace(string(body)) - if len(s) > max { - s = s[:max] - } - r.log.TRACE.Println(s) + bld.WriteString("\n\n") + bld.Write(bytes.TrimSpace(body[:min(max, len(body))])) } } + if bld.Len() > 0 { + r.log.TRACE.Println(bld.String()) + } + return resp, err }