-
Notifications
You must be signed in to change notification settings - Fork 9
feat: add instrument package for Segment #226
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
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
2613ec7
Add instrument package for Segment
keiko713 ea2f7a0
Use TestHook for loging test
keiko713 9c3fb6c
Hide client from the world
keiko713 47ef622
Add documentation for instrument package
keiko713 54a9183
Update comments, hide more things
keiko713 1e10c9a
Add comments to all exposed functions
keiko713 395fe95
Apply reviews
keiko713 eddee48
Expose Client functions too
keiko713 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
package instrument | ||
|
||
type Config struct { | ||
// Write Key for the Segment source | ||
Key string `json:"key" yaml:"key"` | ||
// If this is false, instead of sending the event to Segment, emits verbose log to logger | ||
Enabled bool `json:"enabled" yaml:"enabled" default:"false"` | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
/* | ||
Package instrument provides the tool to emit the events to the instrumentation | ||
destination. Currently it supports Segment or logger as a destination. | ||
|
||
When enabling, make sure to follow the guideline specified in https://github.com/netlify/segment-events | ||
|
||
In the config file, you can define the API key, as well as if it's enabled (use | ||
Segment) or not (use logger). | ||
INSTRUMENT_ENABLED=true | ||
INSTRUMENT_KEY=segment_api_key | ||
|
||
To use, you can import this package: | ||
import "github.com/netlify/netlify-commons/instrument" | ||
|
||
You will likely need to import the Segment's analytics package as well, to | ||
create new traits and properties. | ||
import "gopkg.in/segmentio/analytics-go.v3" | ||
|
||
Then call the functions: | ||
instrument.Track("userid", "service:my_event", analytics.NewProperties().Set("color", "green")) | ||
|
||
For testing, you can create your own mock instrument and use it: | ||
func TestSomething (t *testing.T) { | ||
old := instrument.GetGlobalClient() | ||
t.Cleanup(func(){ instrument.SetGlobalClient(old) }) | ||
instrument.SetGlobalClient(myMockClient) | ||
} | ||
*/ | ||
package instrument |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
package instrument | ||
|
||
import ( | ||
"sync" | ||
|
||
"github.com/sirupsen/logrus" | ||
"gopkg.in/segmentio/analytics-go.v3" | ||
) | ||
|
||
var globalLock sync.Mutex | ||
var globalClient Client = MockClient{} | ||
|
||
func SetGlobalClient(client Client) { | ||
if client == nil { | ||
return | ||
} | ||
globalLock.Lock() | ||
globalClient = client | ||
globalLock.Unlock() | ||
} | ||
|
||
func GetGlobalClient() Client { | ||
globalLock.Lock() | ||
defer globalLock.Unlock() | ||
return globalClient | ||
} | ||
|
||
// Init will initialize global client with a segment client | ||
func Init(conf Config, log logrus.FieldLogger) error { | ||
segmentClient, err := NewClient(&conf, log) | ||
if err != nil { | ||
return err | ||
} | ||
SetGlobalClient(segmentClient) | ||
return nil | ||
} | ||
|
||
// Identify sends an identify type message to a queue to be sent to Segment. | ||
func Identify(userID string, traits analytics.Traits) error { | ||
return GetGlobalClient().Identify(userID, traits) | ||
} | ||
|
||
// Track sends a track type message to a queue to be sent to Segment. | ||
func Track(userID string, event string, properties analytics.Properties) error { | ||
return GetGlobalClient().Track(userID, event, properties) | ||
} | ||
|
||
// Page sends a page type message to a queue to be sent to Segment. | ||
func Page(userID string, name string, properties analytics.Properties) error { | ||
return GetGlobalClient().Page(userID, name, properties) | ||
} | ||
|
||
// Group sends a group type message to a queue to be sent to Segment. | ||
func Group(userID string, groupID string, traits analytics.Traits) error { | ||
return GetGlobalClient().Group(userID, groupID, traits) | ||
} | ||
|
||
// Alias sends an alias type message to a queue to be sent to Segment. | ||
func Alias(previousID string, userID string) error { | ||
return GetGlobalClient().Alias(previousID, userID) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,103 @@ | ||
package instrument | ||
|
||
import ( | ||
"io/ioutil" | ||
|
||
"github.com/sirupsen/logrus" | ||
"gopkg.in/segmentio/analytics-go.v3" | ||
) | ||
|
||
type Client interface { | ||
Identify(userID string, traits analytics.Traits) error | ||
Track(userID string, event string, properties analytics.Properties) error | ||
Page(userID string, name string, properties analytics.Properties) error | ||
Group(userID string, groupID string, traits analytics.Traits) error | ||
Alias(previousID string, userID string) error | ||
} | ||
|
||
type segmentClient struct { | ||
analytics.Client | ||
log logrus.FieldLogger | ||
} | ||
|
||
var _ Client = &segmentClient{} | ||
|
||
func NewClient(cfg *Config, logger logrus.FieldLogger) (Client, error) { | ||
config := analytics.Config{} | ||
|
||
if !cfg.Enabled { | ||
// use mockClient instead | ||
return &MockClient{logger}, nil | ||
} | ||
|
||
configureLogger(&config, logger) | ||
|
||
inner, err := analytics.NewWithConfig(cfg.Key, config) | ||
if err != nil { | ||
logger.WithError(err).Error("Unable to construct Segment client") | ||
} | ||
return &segmentClient{inner, logger}, err | ||
} | ||
|
||
func (c segmentClient) Identify(userID string, traits analytics.Traits) error { | ||
return c.Client.Enqueue(analytics.Identify{ | ||
UserId: userID, | ||
Traits: traits, | ||
}) | ||
} | ||
|
||
func (c segmentClient) Track(userID string, event string, properties analytics.Properties) error { | ||
return c.Client.Enqueue(analytics.Track{ | ||
UserId: userID, | ||
Event: event, | ||
Properties: properties, | ||
}) | ||
} | ||
|
||
func (c segmentClient) Page(userID string, name string, properties analytics.Properties) error { | ||
return c.Client.Enqueue(analytics.Page{ | ||
UserId: userID, | ||
Name: name, | ||
Properties: properties, | ||
}) | ||
} | ||
|
||
func (c segmentClient) Group(userID string, groupID string, traits analytics.Traits) error { | ||
return c.Client.Enqueue(analytics.Group{ | ||
UserId: userID, | ||
GroupId: groupID, | ||
Traits: traits, | ||
}) | ||
} | ||
|
||
func (c segmentClient) Alias(previousID string, userID string) error { | ||
return c.Client.Enqueue(analytics.Alias{ | ||
PreviousId: previousID, | ||
UserId: userID, | ||
}) | ||
} | ||
|
||
func configureLogger(conf *analytics.Config, log logrus.FieldLogger) { | ||
if log == nil { | ||
l := logrus.New() | ||
l.SetOutput(ioutil.Discard) | ||
log = l | ||
} | ||
log = log.WithField("component", "segment") | ||
conf.Logger = &wrapLog{log.Printf, log.Errorf} | ||
} | ||
|
||
type wrapLog struct { | ||
printf func(format string, args ...interface{}) | ||
errorf func(format string, args ...interface{}) | ||
} | ||
|
||
// Logf implements analytics.Logger interface | ||
func (l *wrapLog) Logf(format string, args ...interface{}) { | ||
l.printf(format, args...) | ||
} | ||
|
||
// Errorf implements analytics.Logger interface | ||
func (l *wrapLog) Errorf(format string, args ...interface{}) { | ||
l.errorf(format, args...) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
package instrument | ||
|
||
import ( | ||
"reflect" | ||
"testing" | ||
|
||
"github.com/netlify/netlify-commons/testutil" | ||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
"gopkg.in/segmentio/analytics-go.v3" | ||
) | ||
|
||
func TestLogOnlyClient(t *testing.T) { | ||
cfg := Config{ | ||
Key: "ABCD", | ||
Enabled: false, | ||
} | ||
client, err := NewClient(&cfg, nil) | ||
require.NoError(t, err) | ||
|
||
require.Equal(t, reflect.TypeOf(&MockClient{}).Kind(), reflect.TypeOf(client).Kind()) | ||
} | ||
|
||
func TestMockClient(t *testing.T) { | ||
log := testutil.TL(t) | ||
mock := MockClient{log} | ||
|
||
require.NoError(t, mock.Identify("myuser", analytics.NewTraits().SetName("My User"))) | ||
} | ||
|
||
func TestLogging(t *testing.T) { | ||
cfg := Config{ | ||
Key: "ABCD", | ||
} | ||
|
||
log, hook := testutil.TestLogger(t) | ||
|
||
client, err := NewClient(&cfg, log.WithField("component", "segment")) | ||
require.NoError(t, err) | ||
require.NoError(t, client.Identify("myuser", analytics.NewTraits().SetName("My User"))) | ||
assert.NotEmpty(t, hook.LastEntry()) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
package instrument | ||
|
||
import ( | ||
"github.com/sirupsen/logrus" | ||
"gopkg.in/segmentio/analytics-go.v3" | ||
) | ||
|
||
type MockClient struct { | ||
Logger logrus.FieldLogger | ||
} | ||
|
||
var _ Client = MockClient{} | ||
|
||
func (c MockClient) Identify(userID string, traits analytics.Traits) error { | ||
c.Logger.WithFields(logrus.Fields{ | ||
"user_id": userID, | ||
"traits": traits, | ||
}).Infof("Received Identity event") | ||
return nil | ||
} | ||
|
||
func (c MockClient) Track(userID string, event string, properties analytics.Properties) error { | ||
c.Logger.WithFields(logrus.Fields{ | ||
"user_id": userID, | ||
"event": event, | ||
"properties": properties, | ||
}).Infof("Received Track event") | ||
return nil | ||
} | ||
|
||
func (c MockClient) Page(userID string, name string, properties analytics.Properties) error { | ||
c.Logger.WithFields(logrus.Fields{ | ||
"user_id": userID, | ||
"name": name, | ||
"properties": properties, | ||
}).Infof("Received Page event") | ||
return nil | ||
} | ||
|
||
func (c MockClient) Group(userID string, groupID string, traits analytics.Traits) error { | ||
c.Logger.WithFields(logrus.Fields{ | ||
"user_id": userID, | ||
"group_id": groupID, | ||
"traits": traits, | ||
}).Infof("Received Group event") | ||
return nil | ||
} | ||
|
||
func (c MockClient) Alias(previousID string, userID string) error { | ||
c.Logger.WithFields(logrus.Fields{ | ||
"previous_id": previousID, | ||
"user_id": userID, | ||
}).Infof("Received Alias event") | ||
return nil | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.