pretty-print json in http requests/responses

This commit is contained in:
Dana Hoffman 2018-08-09 12:27:58 -07:00
parent c0793c84fd
commit 40225061b4
1 changed files with 19 additions and 2 deletions

View File

@ -1,9 +1,12 @@
package logging package logging
import ( import (
"bytes"
"encoding/json"
"log" "log"
"net/http" "net/http"
"net/http/httputil" "net/http/httputil"
"strings"
) )
type transport struct { type transport struct {
@ -15,7 +18,7 @@ func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
if IsDebugOrHigher() { if IsDebugOrHigher() {
reqData, err := httputil.DumpRequestOut(req, true) reqData, err := httputil.DumpRequestOut(req, true)
if err == nil { if err == nil {
log.Printf("[DEBUG] "+logReqMsg, t.name, string(reqData)) log.Printf("[DEBUG] "+logReqMsg, t.name, prettyPrintJsonLines(reqData))
} else { } else {
log.Printf("[ERROR] %s API Request error: %#v", t.name, err) 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() { if IsDebugOrHigher() {
respData, err := httputil.DumpResponse(resp, true) respData, err := httputil.DumpResponse(resp, true)
if err == nil { if err == nil {
log.Printf("[DEBUG] "+logRespMsg, t.name, string(respData)) log.Printf("[DEBUG] "+logRespMsg, t.name, prettyPrintJsonLines(respData))
} else { } else {
log.Printf("[ERROR] %s API Response error: %#v", t.name, err) 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} 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: const logReqMsg = `%s API Request Details:
---[ REQUEST ]--------------------------------------- ---[ REQUEST ]---------------------------------------
%s %s