github.com/opentofu/opentofu@v1.7.1/internal/backend/remote-state/azure/sender.go (about)

     1  // Copyright (c) The OpenTofu Authors
     2  // SPDX-License-Identifier: MPL-2.0
     3  // Copyright (c) 2023 HashiCorp, Inc.
     4  // SPDX-License-Identifier: MPL-2.0
     5  
     6  package azure
     7  
     8  import (
     9  	"log"
    10  	"net/http"
    11  	"net/http/httputil"
    12  
    13  	"github.com/Azure/go-autorest/autorest"
    14  	"github.com/opentofu/opentofu/internal/logging"
    15  )
    16  
    17  func buildSender() autorest.Sender {
    18  	return autorest.DecorateSender(&http.Client{
    19  		Transport: &http.Transport{
    20  			Proxy: http.ProxyFromEnvironment,
    21  		},
    22  	}, withRequestLogging())
    23  }
    24  
    25  func withRequestLogging() autorest.SendDecorator {
    26  	return func(s autorest.Sender) autorest.Sender {
    27  		return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) {
    28  			// only log if logging's enabled
    29  			logLevel := logging.CurrentLogLevel()
    30  			if logLevel == "" {
    31  				return s.Do(r)
    32  			}
    33  
    34  			// strip the authorization header prior to printing
    35  			authHeaderName := "Authorization"
    36  			auth := r.Header.Get(authHeaderName)
    37  			if auth != "" {
    38  				r.Header.Del(authHeaderName)
    39  			}
    40  
    41  			// dump request to wire format
    42  			if dump, err := httputil.DumpRequestOut(r, true); err == nil {
    43  				log.Printf("[DEBUG] Azure Backend Request: \n%s\n", dump)
    44  			} else {
    45  				// fallback to basic message
    46  				log.Printf("[DEBUG] Azure Backend Request: %s to %s\n", r.Method, r.URL)
    47  			}
    48  
    49  			// add the auth header back
    50  			if auth != "" {
    51  				r.Header.Add(authHeaderName, auth)
    52  			}
    53  
    54  			resp, err := s.Do(r)
    55  			if resp != nil {
    56  				// dump response to wire format
    57  				if dump, err2 := httputil.DumpResponse(resp, true); err2 == nil {
    58  					log.Printf("[DEBUG] Azure Backend Response for %s: \n%s\n", r.URL, dump)
    59  				} else {
    60  					// fallback to basic message
    61  					log.Printf("[DEBUG] Azure Backend Response: %s for %s\n", resp.Status, r.URL)
    62  				}
    63  			} else {
    64  				log.Printf("[DEBUG] Request to %s completed with no response", r.URL)
    65  			}
    66  			return resp, err
    67  		})
    68  	}
    69  }