github.com/sylr/terraform@v0.11.12-beta1/helper/logging/transport.go (about)

     1  package logging
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"log"
     7  	"net/http"
     8  	"net/http/httputil"
     9  	"strings"
    10  )
    11  
    12  type transport struct {
    13  	name      string
    14  	transport http.RoundTripper
    15  }
    16  
    17  func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
    18  	if IsDebugOrHigher() {
    19  		reqData, err := httputil.DumpRequestOut(req, true)
    20  		if err == nil {
    21  			log.Printf("[DEBUG] "+logReqMsg, t.name, prettyPrintJsonLines(reqData))
    22  		} else {
    23  			log.Printf("[ERROR] %s API Request error: %#v", t.name, err)
    24  		}
    25  	}
    26  
    27  	resp, err := t.transport.RoundTrip(req)
    28  	if err != nil {
    29  		return resp, err
    30  	}
    31  
    32  	if IsDebugOrHigher() {
    33  		respData, err := httputil.DumpResponse(resp, true)
    34  		if err == nil {
    35  			log.Printf("[DEBUG] "+logRespMsg, t.name, prettyPrintJsonLines(respData))
    36  		} else {
    37  			log.Printf("[ERROR] %s API Response error: %#v", t.name, err)
    38  		}
    39  	}
    40  
    41  	return resp, nil
    42  }
    43  
    44  func NewTransport(name string, t http.RoundTripper) *transport {
    45  	return &transport{name, t}
    46  }
    47  
    48  // prettyPrintJsonLines iterates through a []byte line-by-line,
    49  // transforming any lines that are complete json into pretty-printed json.
    50  func prettyPrintJsonLines(b []byte) string {
    51  	parts := strings.Split(string(b), "\n")
    52  	for i, p := range parts {
    53  		if b := []byte(p); json.Valid(b) {
    54  			var out bytes.Buffer
    55  			json.Indent(&out, b, "", " ")
    56  			parts[i] = out.String()
    57  		}
    58  	}
    59  	return strings.Join(parts, "\n")
    60  }
    61  
    62  const logReqMsg = `%s API Request Details:
    63  ---[ REQUEST ]---------------------------------------
    64  %s
    65  -----------------------------------------------------`
    66  
    67  const logRespMsg = `%s API Response Details:
    68  ---[ RESPONSE ]--------------------------------------
    69  %s
    70  -----------------------------------------------------`