Skip to content

Commit

Permalink
Merge pull request #61 from nyaruka/little_less_logging
Browse files Browse the repository at this point in the history
Stop logging all ES requests in debug mode (only log errors)
  • Loading branch information
rowanseymour authored May 22, 2023
2 parents f0cfe11 + 12ec863 commit 69f584a
Showing 1 changed file with 14 additions and 18 deletions.
32 changes: 14 additions & 18 deletions utils/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,43 +50,39 @@ func shouldRetry(request *http.Request, response *http.Response, withDelay time.
}

// MakeJSONRequest is a utility function to make a JSON request, optionally decoding the response into the passed in struct
func MakeJSONRequest(method string, url string, body []byte, jsonStruct interface{}) (*http.Response, error) {
func MakeJSONRequest(method string, url string, body []byte, dest any) (*http.Response, error) {
l := log.WithField("url", url).WithField("method", method)

req, _ := httpx.NewRequest(method, url, bytes.NewReader(body), map[string]string{"Content-Type": "application/json"})
resp, err := httpx.Do(http.DefaultClient, req, retryConfig, nil)

l := log.WithField("url", url).WithField("method", method).WithField("request", body)
if err != nil {
l.WithError(err).Error("error making ES request")
l.WithError(err).Error("error making request")
return resp, err
}
defer resp.Body.Close()

// if we have a body, try to decode it
jsonBody, err := ioutil.ReadAll(resp.Body)
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
l.WithError(err).Error("error reading ES response")
l.WithError(err).Error("error reading response")
return resp, err
}

l = l.WithField("response", string(jsonBody)).WithField("status", resp.StatusCode)
l = l.WithField("response", string(respBody)).WithField("status", resp.StatusCode)

// error if we got a non-200
if resp.StatusCode != http.StatusOK {
l.WithError(err).Error("error reaching ES")
return resp, fmt.Errorf("received non 200 response %d: %s", resp.StatusCode, jsonBody)
}

if jsonStruct == nil {
l.Debug("ES request successful")
return resp, nil
return resp, fmt.Errorf("received non-200 response %d: %s", resp.StatusCode, respBody)
}

err = json.Unmarshal(jsonBody, jsonStruct)
if err != nil {
l.WithError(err).Error("error unmarshalling ES response")
return resp, err
if dest != nil {
err = json.Unmarshal(respBody, dest)
if err != nil {
l.WithError(err).Error("error unmarshalling response")
return resp, err
}
}

l.Debug("ES request successful")
return resp, nil
}

0 comments on commit 69f584a

Please sign in to comment.