Merge pull request #18648 from danawillow/transport

pretty-print json in http requests/responses
This commit is contained in:
Paddy 2018-08-13 13:01:52 -07:00 committed by GitHub
commit fa4ed913e8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 19 additions and 2 deletions

View File

@ -1,9 +1,12 @@
package logging
import (
"bytes"
"encoding/json"
"log"
"net/http"
"net/http/httputil"
"strings"
)
type transport struct {
@ -15,7 +18,7 @@ func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
if IsDebugOrHigher() {
reqData, err := httputil.DumpRequestOut(req, true)
if err == nil {
log.Printf("[DEBUG] "+logReqMsg, t.name, string(reqData))
log.Printf("[DEBUG] "+logReqMsg, t.name, prettyPrintJsonLines(reqData))
} else {
log.Printf("[ERROR] %s API Request error: %#v", t.name, err)
}
@ -29,7 +32,7 @@ func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
if IsDebugOrHigher() {
respData, err := httputil.DumpResponse(resp, true)
if err == nil {
log.Printf("[DEBUG] "+logRespMsg, t.name, string(respData))
log.Printf("[DEBUG] "+logRespMsg, t.name, prettyPrintJsonLines(respData))
} else {
log.Printf("[ERROR] %s API Response error: %#v", t.name, err)
}
@ -42,6 +45,20 @@ func NewTransport(name string, t http.RoundTripper) *transport {
return &transport{name, t}
}
// prettyPrintJsonLines iterates through a []byte line-by-line,
// transforming any lines that are complete json into pretty-printed json.
func prettyPrintJsonLines(b []byte) string {
parts := strings.Split(string(b), "\n")
for i, p := range parts {
if b := []byte(p); json.Valid(b) {
var out bytes.Buffer
json.Indent(&out, b, "", " ")
parts[i] = out.String()
}
}
return strings.Join(parts, "\n")
}
const logReqMsg = `%s API Request Details:
---[ REQUEST ]---------------------------------------
%s