Skip to content

Commit 90f125d

Browse files
author
Mike Davis
authored
Update OptimizelyLogConsumer implementation. (#50)
* Update LogConsumer to use new fields map[string]interface{} parameter * Add log.pretty option within cmd/sidedoor/main.go * Use default zerolog Logger within the Optimizely SDK. * Ran go fmt to get formatting back in line * Ran go mod tidy to get go.mod go.sum back in check
1 parent 518203e commit 90f125d

File tree

10 files changed

+78
-226
lines changed

10 files changed

+78
-226
lines changed

cmd/sidedoor/main.go

Lines changed: 28 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -16,51 +16,57 @@
1616
package main
1717

1818
import (
19-
"github.com/optimizely/sidedoor/pkg/optimizely"
20-
"github.com/optimizely/sidedoor/pkg/webhook/models"
19+
"os"
2120
"strings"
2221
"sync"
2322

23+
"github.com/optimizely/sidedoor/pkg/optimizely"
24+
"github.com/optimizely/sidedoor/pkg/webhook/models"
25+
2426
"github.com/optimizely/sidedoor/pkg/admin"
2527
"github.com/optimizely/sidedoor/pkg/admin/handlers"
2628
"github.com/optimizely/sidedoor/pkg/api"
2729
"github.com/optimizely/sidedoor/pkg/service"
2830
"github.com/optimizely/sidedoor/pkg/webhook"
2931

32+
"github.com/rs/zerolog"
3033
"github.com/rs/zerolog/log"
3134
"github.com/spf13/viper"
3235
)
3336

34-
func loadConfig() {
37+
func loadConfig() error {
38+
39+
// Set defaults
40+
viper.SetDefault("api.enabled", true) // Property to turn api service on/off
41+
viper.SetDefault("api.port", "8080") // Port for serving Optimizely APIs
42+
viper.SetDefault("webhook.enabled", true) // Property to turn webhook service on/off
43+
viper.SetDefault("webhook.port", "8085") // Port for webhook service
44+
viper.SetDefault("admin.port", "8088") // Port for admin service
45+
46+
// Configure environment variables
3547
viper.SetEnvPrefix("sidedoor")
3648
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
49+
viper.AutomaticEnv()
3750

38-
// Set config file
51+
// Read configuration from file
3952
viper.SetConfigName("config")
4053
viper.AddConfigPath(".")
4154
viper.SetConfigType("yaml")
42-
if err := viper.ReadInConfig(); err != nil {
43-
log.Info().Msg("No config file found or config file may have invalid format.")
44-
}
45-
46-
viper.AutomaticEnv()
47-
48-
// Property to turn api service on/off
49-
viper.SetDefault("api.enabled", true)
50-
// Port for serving Optimizely APIs
51-
viper.SetDefault("api.port", "8080")
52-
// Property to turn webhook service on/off
53-
viper.SetDefault("webhook.enabled", true)
54-
// Port for webhook service
55-
viper.SetDefault("webhook.port", "8085")
56-
57-
// Port for admin service
58-
viper.SetDefault("admin.port", "8088")
55+
return viper.ReadInConfig()
5956
}
6057

6158
func main() {
6259

63-
loadConfig()
60+
err := loadConfig()
61+
62+
if viper.GetBool("log.pretty") {
63+
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
64+
}
65+
66+
if err != nil {
67+
log.Info().Err(err).Msg("Ignoring error, skip loading configuration from config.yaml.")
68+
}
69+
6470
var wg sync.WaitGroup
6571

6672
optlyCache := optimizely.NewCache()

go.mod

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,14 @@ go 1.12
55
require (
66
github.com/go-chi/chi v4.0.2+incompatible
77
github.com/go-chi/render v1.0.1
8-
github.com/golangci/golangci-lint v1.18.0 // indirect
98
github.com/google/uuid v1.1.1
109
github.com/nsqio/nsq v1.2.0
11-
github.com/optimizely/go-sdk v1.0.0-beta3
10+
github.com/optimizely/go-sdk v1.0.0-beta3.0.20191018225745-33701145d1ba
1211
github.com/orcaman/concurrent-map v0.0.0-20190826125027-8c72a8bb44f6
1312
github.com/rs/zerolog v1.15.0
1413
github.com/segmentio/nsq-go v1.2.2
1514
github.com/spf13/viper v1.4.0
1615
github.com/stretchr/testify v1.4.0
17-
gopkg.in/yaml.v2 v2.2.2
16+
golang.org/x/net v0.0.0-20190620200207-3b0461eec859 // indirect
17+
golang.org/x/sys v0.0.0-20190312061237-fead79001313 // indirect
1818
)

go.sum

Lines changed: 3 additions & 158 deletions
Large diffs are not rendered by default.

pkg/api/handlers/utils.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ func ParseRequestBody(r *http.Request, v interface{}) error {
5454
if err != nil {
5555
msg := "error parsing request body"
5656
log.Error().Err(err).Msg(msg)
57-
return fmt.Errorf(msg)
57+
return fmt.Errorf(msg)
5858
}
5959

6060
return nil

pkg/optimizely/logger.go

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,26 +18,28 @@
1818
package optimizely
1919

2020
import (
21-
"os"
22-
2321
"github.com/rs/zerolog"
2422
"github.com/rs/zerolog/log"
2523

2624
"github.com/optimizely/go-sdk/pkg/logging"
2725
)
2826

29-
var levelMap = make(map[logging.LogLevel]zerolog.Level)
27+
var levelMap = map[logging.LogLevel]zerolog.Level{
28+
logging.LogLevelDebug: zerolog.DebugLevel,
29+
logging.LogLevelInfo: zerolog.InfoLevel,
30+
logging.LogLevelWarning: zerolog.WarnLevel,
31+
logging.LogLevelError: zerolog.ErrorLevel,
32+
}
3033

31-
// init overrides the Optimizely SDK logger with a logrus implementation.
34+
// init overrides the Optimizely SDK logger with the default zerolog logger.
3235
func init() {
33-
levelMap[logging.LogLevelDebug] = zerolog.DebugLevel
34-
levelMap[logging.LogLevelInfo] = zerolog.InfoLevel
35-
levelMap[logging.LogLevelWarning] = zerolog.WarnLevel
36-
levelMap[logging.LogLevelError] = zerolog.ErrorLevel
36+
SetLogger(&log.Logger)
37+
}
3738

38-
logger := log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
39+
// SetLogger explicitly overwrites the zerolog used by the SDK with the provided zerolog logger.
40+
func SetLogger(logger *zerolog.Logger) {
3941
logConsumer := &LogConsumer{
40-
logger: &logger,
42+
logger: logger,
4143
}
4244

4345
logging.SetLogger(logConsumer)
@@ -49,8 +51,8 @@ type LogConsumer struct {
4951
}
5052

5153
// Log logs the message if it's log level is higher than or equal to the logger's set level
52-
func (l *LogConsumer) Log(level logging.LogLevel, message string) {
53-
l.logger.WithLevel(levelMap[level]).Msg(message)
54+
func (l *LogConsumer) Log(level logging.LogLevel, message string, fields map[string]interface{}) {
55+
l.logger.WithLevel(levelMap[level]).Fields(fields).Msg(message)
5456
}
5557

5658
// SetLogLevel changes the log level to the given level

pkg/optimizely/logger_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,19 +32,19 @@ func TestLog(t *testing.T) {
3232
logger := zerolog.New(out).Level(zerolog.DebugLevel)
3333
logConsumer := &LogConsumer{logger: &logger}
3434

35-
logConsumer.Log(logging.LogLevelDebug, "debug")
35+
logConsumer.Log(logging.LogLevelDebug, "debug", map[string]interface{}{})
3636
assert.Equal(t, "{\"level\":\"debug\",\"message\":\"debug\"}\n", out.String())
3737
out.Reset()
3838

39-
logConsumer.Log(logging.LogLevelInfo, "info")
39+
logConsumer.Log(logging.LogLevelInfo, "info", map[string]interface{}{})
4040
assert.Equal(t, "{\"level\":\"info\",\"message\":\"info\"}\n", out.String())
4141
out.Reset()
4242

43-
logConsumer.Log(logging.LogLevelWarning, "warn")
43+
logConsumer.Log(logging.LogLevelWarning, "warn", map[string]interface{}{})
4444
assert.Equal(t, "{\"level\":\"warn\",\"message\":\"warn\"}\n", out.String())
4545
out.Reset()
4646

47-
logConsumer.Log(logging.LogLevelError, "error")
47+
logConsumer.Log(logging.LogLevelError, "error", map[string]interface{}{})
4848
assert.Equal(t, "{\"level\":\"error\",\"message\":\"error\"}\n", out.String())
4949
out.Reset()
5050
}

pkg/optlytest/cache.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import (
2424

2525
// TestCache implements the Cache interface and is used in testing.
2626
type TestCache struct {
27-
testClient *optimizelytest.TestClient
27+
testClient *optimizelytest.TestClient
2828
}
2929

3030
// NewCache returns a new implementation of TestCache

pkg/webhook/handlers/optimizely_test.go

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ func TestHandleWebhookNoWebhookForProject(t *testing.T) {
4646
ProjectID: 43,
4747
Timestamp: 43434343,
4848
Event: "project.datafile_updated",
49-
Data: models.DatafileUpdateData{
49+
Data: models.DatafileUpdateData{
5050
Revision: 101,
5151
OriginURL: "origin.optimizely.com/datafiles/myDatafile",
5252
CDNUrl: "cdn.optimizely.com/datafiles/myDatafile",
@@ -66,19 +66,19 @@ func TestHandleWebhookNoWebhookForProject(t *testing.T) {
6666
}
6767

6868
func TestHandleWebhookValidMessageInvalidSignature(t *testing.T) {
69-
var testWebhookConfigs = []models.OptlyWebhookConfig {
69+
var testWebhookConfigs = []models.OptlyWebhookConfig{
7070
{
7171
ProjectID: 42,
72-
SDKKeys: []string{"myDatafile"},
73-
Secret: "I am secret",
72+
SDKKeys: []string{"myDatafile"},
73+
Secret: "I am secret",
7474
},
7575
}
7676
optlyHandler := NewWebhookHandler(nil, testWebhookConfigs)
7777
webhookMsg := models.OptlyMessage{
7878
ProjectID: 42,
7979
Timestamp: 42424242,
8080
Event: "project.datafile_updated",
81-
Data: models.DatafileUpdateData{
81+
Data: models.DatafileUpdateData{
8282
Revision: 101,
8383
OriginURL: "origin.optimizely.com/datafiles/myDatafile",
8484
CDNUrl: "cdn.optimizely.com/datafiles/myDatafile",
@@ -99,22 +99,21 @@ func TestHandleWebhookValidMessageInvalidSignature(t *testing.T) {
9999
assert.Regexp(t, "Computed signature does not match signature in request. Ignoring message.", rec.Body.String())
100100
}
101101

102-
103102
func TestHandleWebhookValidMessage(t *testing.T) {
104103
testCache := optlytest.NewCache()
105-
var testWebhookConfigs = []models.OptlyWebhookConfig {
104+
var testWebhookConfigs = []models.OptlyWebhookConfig{
106105
{
107106
ProjectID: 42,
108-
SDKKeys: []string{"myDatafile"},
109-
Secret: "I am secret",
107+
SDKKeys: []string{"myDatafile"},
108+
Secret: "I am secret",
110109
},
111110
}
112111
optlyHandler := NewWebhookHandler(testCache, testWebhookConfigs)
113112
webhookMsg := models.OptlyMessage{
114113
ProjectID: 42,
115114
Timestamp: 42424242,
116115
Event: "project.datafile_updated",
117-
Data: models.DatafileUpdateData{
116+
Data: models.DatafileUpdateData{
118117
Revision: 101,
119118
OriginURL: "origin.optimizely.com/datafiles/myDatafile",
120119
CDNUrl: "cdn.optimizely.com/datafiles/myDatafile",

pkg/webhook/models/optimizely.go

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,23 +19,23 @@ package models
1919

2020
// DatafileUpdateData model which represents data specific to datafile update
2121
type DatafileUpdateData struct {
22-
Revision int32 `json:"revision"`
23-
OriginURL string `json:"origin_url"`
24-
CDNUrl string `json:"cdn_url"`
25-
Environment string `json:"environment"`
22+
Revision int32 `json:"revision"`
23+
OriginURL string `json:"origin_url"`
24+
CDNUrl string `json:"cdn_url"`
25+
Environment string `json:"environment"`
2626
}
2727

2828
// OptlyMessage model which represents any message received from Optimizely
2929
type OptlyMessage struct {
30-
ProjectID int64 `json:"project_id"`
31-
Timestamp int64 `json:"timestamp"`
32-
Event string `json:"event"`
33-
Data DatafileUpdateData `json:"data"`
30+
ProjectID int64 `json:"project_id"`
31+
Timestamp int64 `json:"timestamp"`
32+
Event string `json:"event"`
33+
Data DatafileUpdateData `json:"data"`
3434
}
3535

3636
// OptlyWebhookConfig represents configuration of a single Optimizely webhook
3737
type OptlyWebhookConfig struct {
38-
ProjectID int64 `yaml:"projectId"`
39-
SDKKeys []string `yaml:"sdkKeys"`
40-
Secret string `yaml:"secret"`
38+
ProjectID int64 `yaml:"projectId"`
39+
SDKKeys []string `yaml:"sdkKeys"`
40+
Secret string `yaml:"secret"`
4141
}

pkg/webhook/router.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,15 +28,15 @@ import (
2828

2929
// RouterOptions defines the configuration parameters for Router
3030
type RouterOptions struct {
31-
cache optimizely.Cache
32-
webhookConfigs []models.OptlyWebhookConfig
31+
cache optimizely.Cache
32+
webhookConfigs []models.OptlyWebhookConfig
3333
}
3434

3535
// NewDefaultRouter creates a new router
3636
func NewDefaultRouter(optlyCache optimizely.Cache, webhookConfigs []models.OptlyWebhookConfig) *chi.Mux {
3737
spec := &RouterOptions{
38-
cache: optlyCache,
39-
webhookConfigs: webhookConfigs,
38+
cache: optlyCache,
39+
webhookConfigs: webhookConfigs,
4040
}
4141

4242
return NewRouter(spec)

0 commit comments

Comments
 (0)