Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add SetLogger() method on Request #584

Merged
merged 1 commit into from
Mar 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions client.go
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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