Skip to content

Commit

Permalink
add SetLogger() method on Request (#584)
Browse files Browse the repository at this point in the history
  • Loading branch information
muir committed Mar 6, 2023
1 parent 840c825 commit 64a19d1
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 8 deletions.
1 change: 1 addition & 0 deletions client.go
Expand Up @@ -390,6 +390,7 @@ func (c *Client) R() *Request {
multipartFields: []*MultipartField{},
PathParams: map[string]string{},
jsonEscapeHTML: true,
log: c.log,
}
return r
}
Expand Down
4 changes: 2 additions & 2 deletions middleware.go
Expand Up @@ -233,7 +233,7 @@ func addCredentials(c *Client, r *Request) error {

if !c.DisableWarn {
if isBasicAuth && !strings.HasPrefix(r.URL, "https") {
c.log.Warnf("Using Basic Auth in HTTP mode is not secure, use HTTPS")
r.log.Warnf("Using Basic Auth in HTTP mode is not secure, use HTTPS")
}
}

Expand Down Expand Up @@ -311,7 +311,7 @@ func responseLogger(c *Client, res *Response) error {
}
debugLog += "==============================================================================\n"

c.log.Debugf("%s", debugLog)
res.Request.log.Debugf("%s", debugLog)
}

return nil
Expand Down
14 changes: 12 additions & 2 deletions request.go
Expand Up @@ -65,6 +65,7 @@ type Request struct {
client *Client
bodyBuf *bytes.Buffer
clientTrace *clientTrace
log Logger
multipartFiles []*File
multipartFields []*MultipartField
retryConditions []RetryConditionFunc
Expand Down Expand Up @@ -212,7 +213,7 @@ func (r *Request) SetQueryString(query string) *Request {
}
}
} else {
r.client.log.Errorf("%v", err)
r.log.Errorf("%v", err)
}
return r
}
Expand Down Expand Up @@ -596,6 +597,15 @@ func (r *Request) SetCookies(rs []*http.Cookie) *Request {
return r
}

// SetLogger method sets given writer for logging Resty request and response details.
// By default, requests and responses inherit their logger from the client.
//
// Compliant to interface `resty.Logger`.
func (r *Request) SetLogger(l Logger) *Request {
r.log = l
return r
}

// AddRetryCondition method adds a retry condition function to the request's
// array of functions that are checked to determine if the request is retried.
// The request will retry if any of the functions return true and error is nil.
Expand Down Expand Up @@ -770,7 +780,7 @@ func (r *Request) Execute(method, url string) (*Response, error) {

resp, err = r.client.execute(r)
if err != nil {
r.client.log.Errorf("%v, Attempt %v", err, r.Attempt)
r.log.Errorf("%v, Attempt %v", err, r.Attempt)
}

return resp, err
Expand Down
26 changes: 26 additions & 0 deletions request_test.go
Expand Up @@ -551,6 +551,32 @@ func TestRequestBasicAuth(t *testing.T) {
logResponse(t, resp)
}

func TestRequestInsecureBasicAuth(t *testing.T) {
ts := createAuthServerTLSOptional(t, false)
defer ts.Close()

var logBuf bytes.Buffer
logger := createLogger()
logger.l.SetOutput(&logBuf)

c := dc()
c.SetHostURL(ts.URL)

resp, err := c.R().
SetBasicAuth("myuser", "basicauth").
SetResult(&AuthSuccess{}).
SetLogger(logger).
Post("/login")

assertError(t, err)
assertEqual(t, http.StatusOK, resp.StatusCode())
assertEqual(t, true, strings.Contains(logBuf.String(), "WARN RESTY Using Basic Auth in HTTP mode is not secure, use HTTPS"))

t.Logf("Result Success: %q", resp.Result().(*AuthSuccess))
logResponse(t, resp)
t.Logf("captured request-level logs: %s", logBuf.String())
}

func TestRequestBasicAuthFail(t *testing.T) {
ts := createAuthServer(t)
defer ts.Close()
Expand Down
14 changes: 10 additions & 4 deletions resty_test.go
Expand Up @@ -448,7 +448,11 @@ func createFilePostServer(t *testing.T) *httptest.Server {
}

func createAuthServer(t *testing.T) *httptest.Server {
ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
return createAuthServerTLSOptional(t, true)
}

func createAuthServerTLSOptional(t *testing.T, useTLS bool) *httptest.Server {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Logf("Method: %v", r.Method)
t.Logf("Path: %v", r.URL.Path)
t.Logf("Content-Type: %v", r.Header.Get(hdrContentTypeKey))
Expand Down Expand Up @@ -498,9 +502,11 @@ func createAuthServer(t *testing.T) *httptest.Server {

return
}
}))

return ts
})
if useTLS {
return httptest.NewTLSServer(handler)
}
return httptest.NewServer(handler)
}

func createGenServer(t *testing.T) *httptest.Server {
Expand Down

0 comments on commit 64a19d1

Please sign in to comment.