From f868a59ffaec0f669936046b90c536c710eb3364 Mon Sep 17 00:00:00 2001 From: Radek Simko Date: Wed, 10 May 2017 21:16:43 +0200 Subject: [PATCH] provider/google: Log HTTP requests and responses in DEBUG mode (#14281) --- builtin/providers/google/config.go | 3 ++ helper/logging/transport.go | 53 ++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 helper/logging/transport.go diff --git a/builtin/providers/google/config.go b/builtin/providers/google/config.go index 9ce20633d..716296442 100644 --- a/builtin/providers/google/config.go +++ b/builtin/providers/google/config.go @@ -8,6 +8,7 @@ import ( "runtime" "strings" + "github.com/hashicorp/terraform/helper/logging" "github.com/hashicorp/terraform/helper/pathorcontents" "github.com/hashicorp/terraform/terraform" "golang.org/x/oauth2" @@ -95,6 +96,8 @@ func (c *Config) loadAndValidate() error { } } + client.Transport = logging.NewTransport("Google", client.Transport) + versionString := terraform.VersionString() userAgent := fmt.Sprintf( "(%s %s) Terraform/%s", runtime.GOOS, runtime.GOARCH, versionString) diff --git a/helper/logging/transport.go b/helper/logging/transport.go new file mode 100644 index 000000000..447792487 --- /dev/null +++ b/helper/logging/transport.go @@ -0,0 +1,53 @@ +package logging + +import ( + "log" + "net/http" + "net/http/httputil" +) + +type transport struct { + name string + transport http.RoundTripper +} + +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)) + } else { + log.Printf("[ERROR] %s API Request error: %#v", t.name, err) + } + } + + resp, err := t.transport.RoundTrip(req) + if err != nil { + return resp, err + } + + if IsDebugOrHigher() { + respData, err := httputil.DumpResponse(resp, true) + if err == nil { + log.Printf("[DEBUG] "+logRespMsg, t.name, string(respData)) + } else { + log.Printf("[ERROR] %s API Response error: %#v", t.name, err) + } + } + + return resp, nil +} + +func NewTransport(name string, t http.RoundTripper) *transport { + return &transport{name, t} +} + +const logReqMsg = `%s API Request Details: +---[ REQUEST ]--------------------------------------- +%s +-----------------------------------------------------` + +const logRespMsg = `%s API Response Details: +---[ RESPONSE ]-------------------------------------- +%s +-----------------------------------------------------`