Skip to content

Commit a818d55

Browse files
committed
Logger renamed to Sugar
1 parent 64f6139 commit a818d55

File tree

5 files changed

+49
-44
lines changed

5 files changed

+49
-44
lines changed

httpclient/client.go

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ type Client struct {
2727

2828
AuthToken string
2929
AuthTokenExpiry time.Time
30-
Logger *zap.SugaredLogger
30+
Sugar *zap.SugaredLogger
3131
Concurrency *concurrency.ConcurrencyHandler
3232
Integration *APIIntegration
3333
}
@@ -80,7 +80,16 @@ type ClientConfig struct {
8080
}
8181

8282
// BuildClient creates a new HTTP client with the provided configuration.
83-
func (c ClientConfig) BuildClient(populateDefaultValues bool, logger *zap.SugaredLogger) (*Client, error) {
83+
func (c ClientConfig) BuildClient(populateDefaultValues bool, sugar *zap.SugaredLogger) (*Client, error) {
84+
85+
if sugar == nil {
86+
zapLogger, err := zap.NewProduction()
87+
sugar = zapLogger.Sugar()
88+
89+
if err != nil {
90+
return nil, err
91+
}
92+
}
8493

8594
err := c.validateClientConfig(populateDefaultValues)
8695
if err != nil {
@@ -92,7 +101,7 @@ func (c ClientConfig) BuildClient(populateDefaultValues bool, logger *zap.Sugare
92101
}
93102

94103
// TODO refactor redirects
95-
if err := redirecthandler.SetupRedirectHandler(httpClient, c.FollowRedirects, c.MaxRedirects, logger); err != nil {
104+
if err := redirecthandler.SetupRedirectHandler(httpClient, c.FollowRedirects, c.MaxRedirects, sugar); err != nil {
96105
return nil, fmt.Errorf("Failed to set up redirect handler: %v", err)
97106
}
98107

@@ -101,7 +110,7 @@ func (c ClientConfig) BuildClient(populateDefaultValues bool, logger *zap.Sugare
101110
concurrencyMetrics := &concurrency.ConcurrencyMetrics{}
102111
concurrencyHandler = concurrency.NewConcurrencyHandler(
103112
c.MaxConcurrentRequests,
104-
logger,
113+
sugar,
105114
concurrencyMetrics,
106115
)
107116
} else {
@@ -112,7 +121,7 @@ func (c ClientConfig) BuildClient(populateDefaultValues bool, logger *zap.Sugare
112121
Integration: &c.Integration,
113122
http: httpClient,
114123
config: c,
115-
Logger: logger,
124+
Sugar: sugar,
116125
Concurrency: concurrencyHandler,
117126
}
118127

httpclient/headers.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@ import (
88
)
99

1010
// CheckDeprecationHeader checks the response headers for the Deprecation header and logs a warning if present.
11-
func CheckDeprecationHeader(resp *http.Response, log *zap.SugaredLogger) {
11+
func CheckDeprecationHeader(resp *http.Response, sugar *zap.SugaredLogger) {
1212
deprecationHeader := resp.Header.Get("Deprecation")
1313
if deprecationHeader != "" {
14-
log.Warn("API endpoint is deprecated",
14+
sugar.Warn("API endpoint is deprecated",
1515
zap.String("Date", deprecationHeader),
1616
zap.String("Endpoint", resp.Request.URL.String()),
1717
)

httpclient/multipartrequest.go

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -66,10 +66,9 @@ type UploadState struct {
6666
//
6767
// // Use `result` or `resp` as needed
6868
func (c *Client) DoMultiPartRequest(method, endpoint string, files map[string][]string, formDataFields map[string]string, fileContentTypes map[string]string, formDataPartHeaders map[string]http.Header, out interface{}) (*http.Response, error) {
69-
log := c.Logger
7069

7170
if method != http.MethodPost && method != http.MethodPut {
72-
log.Error("HTTP method not supported for multipart request", zap.String("method", method))
71+
c.Sugar.Error("HTTP method not supported for multipart request", zap.String("method", method))
7372
return nil, fmt.Errorf("unsupported HTTP method: %s", method)
7473
}
7574

@@ -80,11 +79,11 @@ func (c *Client) DoMultiPartRequest(method, endpoint string, files map[string][]
8079

8180
if c.config.CustomTimeout > 0 {
8281
ctx, cancel = context.WithTimeout(context.Background(), c.config.CustomTimeout)
83-
log.Info("Using timeout context for multipart request", zap.Duration("custom_timeout_seconds", c.config.CustomTimeout))
82+
c.Sugar.Info("Using timeout context for multipart request", zap.Duration("custom_timeout_seconds", c.config.CustomTimeout))
8483
} else {
8584
ctx = context.Background()
8685
cancel = func() {}
87-
log.Info("Using background context for multipart request. Caller will handle timeouts")
86+
c.Sugar.Info("Using background context for multipart request. Caller will handle timeouts")
8887
}
8988
defer cancel()
9089

@@ -94,28 +93,28 @@ func (c *Client) DoMultiPartRequest(method, endpoint string, files map[string][]
9493
// Create multipart body in a function to ensure it runs again on retry
9594
createBody := func() error {
9695
var err error
97-
body, contentType, err = createStreamingMultipartRequestBody(files, formDataFields, fileContentTypes, formDataPartHeaders, log)
96+
body, contentType, err = createStreamingMultipartRequestBody(files, formDataFields, fileContentTypes, formDataPartHeaders, c.Sugar)
9897
if err != nil {
99-
log.Error("Failed to create streaming multipart request body", zap.Error(err))
98+
c.Sugar.Error("Failed to create streaming multipart request body", zap.Error(err))
10099
} else {
101-
log.Info("Successfully created streaming multipart request body", zap.String("content_type", contentType))
100+
c.Sugar.Info("Successfully created streaming multipart request body", zap.String("content_type", contentType))
102101
}
103102
return err
104103
}
105104

106105
if err := createBody(); err != nil {
107-
log.Error("Failed to create streaming multipart request body", zap.Error(err))
106+
c.Sugar.Error("Failed to create streaming multipart request body", zap.Error(err))
108107
return nil, err
109108
}
110109

111110
req, err := http.NewRequestWithContext(ctx, method, url, body)
112111
if err != nil {
113-
log.Error("Failed to create HTTP request", zap.Error(err))
112+
c.Sugar.Error("Failed to create HTTP request", zap.Error(err))
114113
return nil, err
115114
}
116115

117116
// Log the request details
118-
log.Info("Created HTTP Multipart request", zap.String("method", method), zap.String("url", url), zap.String("content_type", contentType))
117+
c.Sugar.Info("Created HTTP Multipart request", zap.String("method", method), zap.String("url", url), zap.String("content_type", contentType))
119118

120119
(*c.Integration).PrepRequestParamsAndAuth(req)
121120

@@ -126,17 +125,17 @@ func (c *Client) DoMultiPartRequest(method, endpoint string, files map[string][]
126125
duration := time.Since(startTime)
127126

128127
if requestErr != nil {
129-
log.Error("Failed to send request", zap.String("method", method), zap.String("endpoint", endpoint), zap.Error(requestErr))
128+
c.Sugar.Error("Failed to send request", zap.String("method", method), zap.String("endpoint", endpoint), zap.Error(requestErr))
130129
return nil, requestErr
131130
}
132131

133-
log.Debug("Request sent successfully", zap.String("method", method), zap.String("endpoint", endpoint), zap.Int("status_code", resp.StatusCode), zap.Duration("duration", duration))
132+
c.Sugar.Debug("Request sent successfully", zap.String("method", method), zap.String("endpoint", endpoint), zap.Int("status_code", resp.StatusCode), zap.Duration("duration", duration))
134133

135134
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
136-
return resp, response.HandleAPISuccessResponse(resp, out, log)
135+
return resp, response.HandleAPISuccessResponse(resp, out, c.Sugar)
137136
}
138137

139-
return resp, response.HandleAPIErrorResponse(resp, log)
138+
return resp, response.HandleAPIErrorResponse(resp, c.Sugar)
140139
}
141140

142141
// createStreamingMultipartRequestBody creates a streaming multipart request body with the provided files and form fields.

httpclient/request.go

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -115,15 +115,14 @@ func (c *Client) DoRequest(method, endpoint string, body, out interface{}) (*htt
115115
// endregion
116116
func (c *Client) executeRequestWithRetries(method, endpoint string, body, out interface{}) (*http.Response, error) {
117117
// TODO review refactor executeRequestWithRetries
118-
log := c.Logger
119118
ctx := context.Background()
120119
totalRetryDeadline := time.Now().Add(c.config.TotalRetryDuration)
121120

122121
var resp *http.Response
123122
var err error
124123
var retryCount int
125124

126-
log.Debug("Executing request with retries", zap.String("method", method), zap.String("endpoint", endpoint))
125+
c.Sugar.Debug("Executing request with retries", zap.String("method", method), zap.String("endpoint", endpoint))
127126

128127
for time.Now().Before(totalRetryDeadline) {
129128
res, requestErr := c.doRequest(ctx, method, endpoint, body)
@@ -134,22 +133,22 @@ func (c *Client) executeRequestWithRetries(method, endpoint string, body, out in
134133

135134
if resp.StatusCode >= 200 && resp.StatusCode < 400 {
136135
if resp.StatusCode >= 300 {
137-
log.Warn("Redirect response received", zap.Int("status_code", resp.StatusCode), zap.String("location", resp.Header.Get("Location")))
136+
c.Sugar.Warn("Redirect response received", zap.Int("status_code", resp.StatusCode), zap.String("location", resp.Header.Get("Location")))
138137
}
139-
return resp, response.HandleAPISuccessResponse(resp, out, log)
138+
return resp, response.HandleAPISuccessResponse(resp, out, c.Sugar)
140139
}
141140

142141
statusMessage := status.TranslateStatusCode(resp)
143142

144143
if resp != nil && status.IsNonRetryableStatusCode(resp) {
145-
log.Warn("Non-retryable error received", zap.Int("status_code", resp.StatusCode), zap.String("status_message", statusMessage))
146-
return resp, response.HandleAPIErrorResponse(resp, log)
144+
c.Sugar.Warn("Non-retryable error received", zap.Int("status_code", resp.StatusCode), zap.String("status_message", statusMessage))
145+
return resp, response.HandleAPIErrorResponse(resp, c.Sugar)
147146
}
148147

149148
if status.IsRateLimitError(resp) {
150-
waitDuration := ratehandler.ParseRateLimitHeaders(resp, log)
149+
waitDuration := ratehandler.ParseRateLimitHeaders(resp, c.Sugar)
151150
if waitDuration > 0 {
152-
log.Warn("Rate limit encountered, waiting before retrying", zap.Duration("waitDuration", waitDuration))
151+
c.Sugar.Warn("Rate limit encountered, waiting before retrying", zap.Duration("waitDuration", waitDuration))
153152
time.Sleep(waitDuration)
154153
continue
155154
}
@@ -158,17 +157,17 @@ func (c *Client) executeRequestWithRetries(method, endpoint string, body, out in
158157
if status.IsTransientError(resp) {
159158
retryCount++
160159
if retryCount > c.config.MaxRetryAttempts {
161-
log.Warn("Max retry attempts reached", zap.String("method", method), zap.String("endpoint", endpoint))
160+
c.Sugar.Warn("Max retry attempts reached", zap.String("method", method), zap.String("endpoint", endpoint))
162161
break
163162
}
164163
waitDuration := ratehandler.CalculateBackoff(retryCount)
165-
log.Warn("Retrying request due to transient error", zap.String("method", method), zap.String("endpoint", endpoint), zap.Int("retryCount", retryCount), zap.Duration("waitDuration", waitDuration), zap.Error(err))
164+
c.Sugar.Warn("Retrying request due to transient error", zap.String("method", method), zap.String("endpoint", endpoint), zap.Int("retryCount", retryCount), zap.Duration("waitDuration", waitDuration), zap.Error(err))
166165
time.Sleep(waitDuration)
167166
continue
168167
}
169168

170169
if !status.IsRetryableStatusCode(resp.StatusCode) {
171-
if apiErr := response.HandleAPIErrorResponse(resp, log); apiErr != nil {
170+
if apiErr := response.HandleAPIErrorResponse(resp, c.Sugar); apiErr != nil {
172171
err = apiErr
173172
}
174173
break
@@ -179,7 +178,7 @@ func (c *Client) executeRequestWithRetries(method, endpoint string, body, out in
179178
return nil, err
180179
}
181180

182-
return resp, response.HandleAPIErrorResponse(resp, log)
181+
return resp, response.HandleAPIErrorResponse(resp, c.Sugar)
183182
}
184183

185184
// region comment
@@ -216,10 +215,10 @@ func (c *Client) executeRequestWithRetries(method, endpoint string, body, out in
216215
// endregion
217216
func (c *Client) executeRequest(method, endpoint string, body, out interface{}) (*http.Response, error) {
218217
// TODO review refactor execute Request
219-
log := c.Logger
218+
220219
ctx := context.Background()
221220

222-
log.Debug("Executing request without retries", zap.String("method", method), zap.String("endpoint", endpoint))
221+
c.Sugar.Debug("Executing request without retries", zap.String("method", method), zap.String("endpoint", endpoint))
223222

224223
res, err := c.doRequest(ctx, method, endpoint, body)
225224
if err != nil {
@@ -228,12 +227,12 @@ func (c *Client) executeRequest(method, endpoint string, body, out interface{})
228227

229228
if res.StatusCode >= 200 && res.StatusCode < 400 {
230229
if res.StatusCode >= 300 {
231-
log.Warn("Redirect response received", zap.Int("status_code", res.StatusCode), zap.String("location", res.Header.Get("Location")))
230+
c.Sugar.Warn("Redirect response received", zap.Int("status_code", res.StatusCode), zap.String("location", res.Header.Get("Location")))
232231
}
233-
return res, response.HandleAPISuccessResponse(res, out, log)
232+
return res, response.HandleAPISuccessResponse(res, out, c.Sugar)
234233
}
235234

236-
return nil, response.HandleAPIErrorResponse(res, log)
235+
return nil, response.HandleAPIErrorResponse(res, c.Sugar)
237236
}
238237

239238
func (c *Client) doRequest(ctx context.Context, method, endpoint string, body interface{}) (*http.Response, error) {
@@ -280,7 +279,7 @@ func (c *Client) doRequest(ctx context.Context, method, endpoint string, body in
280279

281280
resp, err := c.http.Do(req)
282281
if err != nil {
283-
c.Logger.Error("Failed to send request", zap.String("method", method), zap.String("endpoint", endpoint), zap.Error(err))
282+
c.Sugar.Error("Failed to send request", zap.String("method", method), zap.String("endpoint", endpoint), zap.Error(err))
284283
return nil, err
285284
}
286285

@@ -292,9 +291,9 @@ func (c *Client) doRequest(ctx context.Context, method, endpoint string, body in
292291

293292
// TODO review LogCookies
294293

295-
CheckDeprecationHeader(resp, c.Logger)
294+
CheckDeprecationHeader(resp, c.Sugar)
296295

297-
c.Logger.Debug("Request sent successfully", zap.String("method", method), zap.String("endpoint", endpoint), zap.Int("status_code", resp.StatusCode))
296+
c.Sugar.Debug("Request sent successfully", zap.String("method", method), zap.String("endpoint", endpoint), zap.Int("status_code", resp.StatusCode))
298297

299298
time.Sleep(c.config.MandatoryRequestDelay)
300299

response/success.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -118,9 +118,7 @@ func handleBinaryData(reader io.Reader, log *zap.SugaredLogger, out interface{},
118118
}
119119

120120
default:
121-
errMsg := "output parameter is not suitable for binary data (*[]byte or io.Writer)"
122-
log.Error(errMsg, zap.String("Content-Type", mimeType))
123-
return errors.New(errMsg)
121+
return errors.New("output parameter is not suitable for binary data (*[]byte or io.Writer)")
124122
}
125123

126124
// Handle Content-Disposition if present

0 commit comments

Comments
 (0)