Skip to content

Commit 275ac33

Browse files
authored
Merge pull request #254 from deploymenttheory/dev-jl-logging
Logging Refactor - Moved to zap.SugaredLogger
2 parents 3d99151 + 2417d33 commit 275ac33

24 files changed

+188
-1171
lines changed

concurrency/handler.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,13 @@ import (
55
"sync"
66
"time"
77

8-
"github.com/deploymenttheory/go-api-http-client/logger"
8+
"go.uber.org/zap"
99
)
1010

1111
// ConcurrencyHandler controls the number of concurrent HTTP requests.
1212
type ConcurrencyHandler struct {
1313
sem chan struct{}
14-
logger logger.Logger
14+
logger *zap.SugaredLogger
1515
AcquisitionTimes []time.Duration
1616
lock sync.Mutex
1717
lastTokenAcquisitionTime time.Time
@@ -55,7 +55,7 @@ type ConcurrencyMetrics struct {
5555
// concurrency limit, logger, and concurrency metrics. The ConcurrencyHandler ensures
5656
// no more than a certain number of concurrent requests are made.
5757
// It uses a semaphore to control concurrency.
58-
func NewConcurrencyHandler(limit int, logger logger.Logger, metrics *ConcurrencyMetrics) *ConcurrencyHandler {
58+
func NewConcurrencyHandler(limit int, logger *zap.SugaredLogger, metrics *ConcurrencyMetrics) *ConcurrencyHandler {
5959
return &ConcurrencyHandler{
6060
sem: make(chan struct{}, limit),
6161
logger: logger,

httpclient/client.go

+50-36
Original file line numberDiff line numberDiff line change
@@ -13,31 +13,44 @@ import (
1313
"time"
1414

1515
"github.com/deploymenttheory/go-api-http-client/concurrency"
16+
"go.uber.org/zap"
1617

17-
"github.com/deploymenttheory/go-api-http-client/logger"
1818
"github.com/deploymenttheory/go-api-http-client/redirecthandler"
19-
"go.uber.org/zap"
2019
)
2120

21+
const ()
22+
2223
// TODO all struct comments
2324

2425
// Master struct/object
2526
type Client struct {
26-
config ClientConfig
27-
http *http.Client
28-
29-
AuthToken string
30-
AuthTokenExpiry time.Time
31-
Logger logger.Logger
32-
Concurrency *concurrency.ConcurrencyHandler
33-
Integration *APIIntegration
27+
// Config
28+
config *ClientConfig
29+
30+
// Integration
31+
Integration *APIIntegration
32+
33+
// Executor
34+
http *http.Client
35+
36+
// Logger
37+
Sugar *zap.SugaredLogger
38+
39+
// Concurrency Mananger
40+
Concurrency *concurrency.ConcurrencyHandler
3441
}
3542

3643
// Options/Variables for Client
3744
type ClientConfig struct {
3845
// Interface which implements the APIIntegration patterns. Integration handles all server/endpoint specific configuration, auth and vars.
3946
Integration APIIntegration
4047

48+
// TODO
49+
Sugar *zap.SugaredLogger
50+
51+
// Wether or not empty values will be set or an error thrown for missing items.
52+
PopulateDefaultValues bool
53+
4154
// HideSenitiveData controls if sensitive data will be visible in logs. Debug option which should be True in production use.
4255
HideSensitiveData bool `json:"hide_sensitive_data"`
4356

@@ -81,60 +94,61 @@ type ClientConfig struct {
8194
}
8295

8396
// BuildClient creates a new HTTP client with the provided configuration.
84-
func BuildClient(config ClientConfig, populateDefaultValues bool, log logger.Logger) (*Client, error) {
85-
err := validateClientConfig(config, populateDefaultValues)
97+
func (c *ClientConfig) Build() (*Client, error) {
98+
if c.Sugar == nil {
99+
zapLogger, err := zap.NewProduction()
100+
if err != nil {
101+
return nil, err
102+
}
103+
104+
c.Sugar = zapLogger.Sugar()
105+
c.Sugar.Info("No logger provided. Defaulting to Sugared Zap Production Logger")
106+
}
107+
108+
c.Sugar.Debug("validating configuration")
109+
110+
err := c.validateClientConfig()
86111
if err != nil {
87112
return nil, fmt.Errorf("invalid configuration: %v", err)
88113
}
89-
90-
log.Info(fmt.Sprintf("initializing new http client, auth: %s", config.Integration.GetFQDN()))
114+
c.Sugar.Debug("configuration valid")
91115

92116
httpClient := &http.Client{
93-
Timeout: config.CustomTimeout,
117+
Timeout: c.CustomTimeout,
94118
}
95119

96120
// TODO refactor redirects
97-
if err := redirecthandler.SetupRedirectHandler(httpClient, config.FollowRedirects, config.MaxRedirects, log); err != nil {
121+
if err := redirecthandler.SetupRedirectHandler(httpClient, c.FollowRedirects, c.MaxRedirects, c.Sugar); err != nil {
98122
return nil, fmt.Errorf("Failed to set up redirect handler: %v", err)
99123
}
100124

125+
// TODO refactor concurrency
101126
var concurrencyHandler *concurrency.ConcurrencyHandler
102-
if config.EnableConcurrencyManagement {
127+
if c.EnableConcurrencyManagement {
103128
concurrencyMetrics := &concurrency.ConcurrencyMetrics{}
104129
concurrencyHandler = concurrency.NewConcurrencyHandler(
105-
config.MaxConcurrentRequests,
106-
log,
130+
c.MaxConcurrentRequests,
131+
c.Sugar,
107132
concurrencyMetrics,
108133
)
109134
} else {
110135
concurrencyHandler = nil
111136
}
112137

113138
client := &Client{
114-
Integration: &config.Integration,
139+
Integration: &c.Integration,
115140
http: httpClient,
116-
config: config,
117-
Logger: log,
141+
config: c,
142+
Sugar: c.Sugar,
118143
Concurrency: concurrencyHandler,
119144
}
120145

121146
if len(client.config.CustomCookies) > 0 {
122-
client.loadCustomCookies(config.CustomCookies)
147+
client.Sugar.Debug("setting custom cookies")
148+
client.loadCustomCookies()
123149
}
124150

125-
log.Debug("New API client initialized",
126-
zap.String("Authentication Method", (*client.Integration).GetAuthMethodDescriptor()),
127-
zap.Bool("Hide Sensitive Data In Logs", config.HideSensitiveData),
128-
zap.Int("Max Retry Attempts", config.MaxRetryAttempts),
129-
zap.Bool("Enable Dynamic Rate Limiting", config.EnableDynamicRateLimiting),
130-
zap.Int("Max Concurrent Requests", config.MaxConcurrentRequests),
131-
zap.Bool("Follow Redirects", config.FollowRedirects),
132-
zap.Int("Max Redirects", config.MaxRedirects),
133-
zap.Duration("Token Refresh Buffer Period", config.TokenRefreshBufferPeriod),
134-
zap.Duration("Total Retry Duration", config.TotalRetryDuration),
135-
zap.Duration("Custom Timeout", config.CustomTimeout),
136-
zap.Bool("Enable Concurrency Management", config.EnableConcurrencyManagement),
137-
)
151+
client.Sugar.Infof("client init complete: %+v", client)
138152

139153
return client, nil
140154

httpclient/config_validation.go

+24-24
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ func LoadConfigFromFile(filepath string) (*ClientConfig, error) {
5555
return nil, fmt.Errorf("could not unmarshal JSON: %v", err)
5656
}
5757

58-
SetDefaultValuesClientConfig(&config)
58+
config.SetDefaultValuesClientConfig()
5959

6060
return &config, nil
6161
}
@@ -96,43 +96,43 @@ func LoadConfigFromEnv() (*ClientConfig, error) {
9696
}
9797

9898
// TODO Review validateClientConfig
99-
func validateClientConfig(config ClientConfig, populateDefaults bool) error {
99+
func (c ClientConfig) validateClientConfig() error {
100100

101-
if populateDefaults {
102-
SetDefaultValuesClientConfig(&config)
101+
if c.PopulateDefaultValues {
102+
c.SetDefaultValuesClientConfig()
103103
}
104104

105105
// TODO adjust these strings to have links to documentation & centralise them
106-
if config.Integration == nil {
106+
if c.Integration == nil {
107107
return errors.New("no http client api integration supplied, please see repo documentation for this client and go-api-http-client-integration and provide an implementation")
108108
}
109109

110-
if config.EnableConcurrencyManagement {
111-
if config.MaxConcurrentRequests < 1 {
110+
if c.EnableConcurrencyManagement {
111+
if c.MaxConcurrentRequests < 1 {
112112
return errors.New("maximum concurrent requests cannot be less than 1")
113113
}
114114
}
115115

116-
if config.CustomTimeout.Seconds() < 0 {
116+
if c.CustomTimeout.Seconds() < 0 {
117117
return errors.New("timeout cannot be less than 0 seconds")
118118
}
119119

120-
if config.TokenRefreshBufferPeriod.Seconds() < 0 {
120+
if c.TokenRefreshBufferPeriod.Seconds() < 0 {
121121
return errors.New("refresh buffer period cannot be less than 0 seconds")
122122
}
123123

124-
if config.RetryEligiableRequests {
125-
if config.TotalRetryDuration.Seconds() < 0 {
124+
if c.RetryEligiableRequests {
125+
if c.TotalRetryDuration.Seconds() < 0 {
126126
return errors.New("total retry duration cannot be less than 0 seconds")
127127
}
128128

129-
if config.MaxRetryAttempts < 0 {
129+
if c.MaxRetryAttempts < 0 {
130130
return errors.New("max retry cannot be less than 0")
131131
}
132132

133133
}
134134

135-
if config.FollowRedirects {
135+
if c.FollowRedirects {
136136
if DefaultMaxRedirects < 1 {
137137
return errors.New("max redirects cannot be less than 1")
138138
}
@@ -142,15 +142,15 @@ func validateClientConfig(config ClientConfig, populateDefaults bool) error {
142142
}
143143

144144
// SetDefaultValuesClientConfig sets default values for the client configuration. Ensuring that all fields have a valid or minimum value.
145-
func SetDefaultValuesClientConfig(config *ClientConfig) {
146-
setDefaultBool(&config.HideSensitiveData, DefaultHideSensitiveData)
147-
setDefaultInt(&config.MaxRetryAttempts, DefaultMaxRetryAttempts, 1)
148-
setDefaultInt(&config.MaxConcurrentRequests, DefaultMaxConcurrentRequests, 1)
149-
setDefaultBool(&config.EnableDynamicRateLimiting, DefaultEnableDynamicRateLimiting)
150-
setDefaultDuration(&config.CustomTimeout, DefaultCustomTimeout)
151-
setDefaultDuration(&config.TokenRefreshBufferPeriod, DefaultTokenRefreshBufferPeriod)
152-
setDefaultDuration(&config.TotalRetryDuration, DefaultTotalRetryDuration)
153-
setDefaultBool(&config.FollowRedirects, DefaultFollowRedirects)
154-
setDefaultInt(&config.MaxRedirects, DefaultMaxRedirects, 0)
155-
setDefaultBool(&config.EnableConcurrencyManagement, DefaultEnableConcurrencyManagement)
145+
func (c *ClientConfig) SetDefaultValuesClientConfig() {
146+
setDefaultBool(&c.HideSensitiveData, DefaultHideSensitiveData)
147+
setDefaultInt(&c.MaxRetryAttempts, DefaultMaxRetryAttempts, 1)
148+
setDefaultInt(&c.MaxConcurrentRequests, DefaultMaxConcurrentRequests, 1)
149+
setDefaultBool(&c.EnableDynamicRateLimiting, DefaultEnableDynamicRateLimiting)
150+
setDefaultDuration(&c.CustomTimeout, DefaultCustomTimeout)
151+
setDefaultDuration(&c.TokenRefreshBufferPeriod, DefaultTokenRefreshBufferPeriod)
152+
setDefaultDuration(&c.TotalRetryDuration, DefaultTotalRetryDuration)
153+
setDefaultBool(&c.FollowRedirects, DefaultFollowRedirects)
154+
setDefaultInt(&c.MaxRedirects, DefaultMaxRedirects, 0)
155+
setDefaultBool(&c.EnableConcurrencyManagement, DefaultEnableConcurrencyManagement)
156156
}

httpclient/cookies.go

+4-7
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,24 @@
11
package httpclient
22

33
import (
4-
"fmt"
5-
"net/http"
64
"net/http/cookiejar"
75
"net/url"
86
)
97

10-
func (c *Client) loadCustomCookies(cookiesList []*http.Cookie) error {
8+
func (c *Client) loadCustomCookies() error {
119
cookieJar, err := cookiejar.New(nil)
1210
if err != nil {
1311
return err
1412
}
13+
c.http.Jar = cookieJar
1514

1615
cookieUrl, err := url.Parse((*c.Integration).GetFQDN())
17-
1816
if err != nil {
1917
return err
2018
}
2119

22-
c.http.Jar = cookieJar
23-
c.http.Jar.SetCookies(cookieUrl, cookiesList)
24-
c.Logger.Debug(fmt.Sprintf("%+v", c.http.Jar))
20+
c.http.Jar.SetCookies(cookieUrl, c.config.CustomCookies)
21+
c.Sugar.Debug("custom cookies set: %v", c.http.Jar.Cookies(cookieUrl))
2522

2623
return nil
2724
}

httpclient/headers.go

+2-9
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,12 @@ package httpclient
33

44
import (
55
"net/http"
6-
7-
"github.com/deploymenttheory/go-api-http-client/logger"
8-
"go.uber.org/zap"
96
)
107

118
// CheckDeprecationHeader checks the response headers for the Deprecation header and logs a warning if present.
12-
func CheckDeprecationHeader(resp *http.Response, log logger.Logger) {
9+
func (c *Client) CheckDeprecationHeader(resp *http.Response) {
1310
deprecationHeader := resp.Header.Get("Deprecation")
1411
if deprecationHeader != "" {
15-
16-
log.Warn("API endpoint is deprecated",
17-
zap.String("Date", deprecationHeader),
18-
zap.String("Endpoint", resp.Request.URL.String()),
19-
)
12+
c.Sugar.Warn("API endpoint is deprecated", deprecationHeader, resp.Request.URL.String())
2013
}
2114
}

0 commit comments

Comments
 (0)