Codebase list golang-github-go-kit-kit / 002c376
Use Cloudwatch options in the struct itself, which is cleaner Eric Feliksik 6 years ago
1 changed file(s) with 30 addition(s) and 34 deletion(s). Raw diff Collapse all Expand all
3030 //
3131 // To regularly report metrics to CloudWatch, use the WriteLoop helper method.
3232 type CloudWatch struct {
33 mtx sync.RWMutex
34 sem chan struct{}
35 namespace string
36 svc cloudwatchiface.CloudWatchAPI
37 counters *lv.Space
38 gauges *lv.Space
39 histograms *lv.Space
40 *cwoptions
41 }
42
43 type cwoptions struct {
33 mtx sync.RWMutex
34 sem chan struct{}
35 namespace string
36 svc cloudwatchiface.CloudWatchAPI
37 counters *lv.Space
38 gauges *lv.Space
39 histograms *lv.Space
4440 percentiles Percentiles
4541 logger log.Logger
4642 numConcurrentRequests int
4743 }
4844
49 type option func(*cwoptions)
50
51 func (s *cwoptions) apply(opt option) {
45 type option func(*CloudWatch)
46
47 func (s *CloudWatch) apply(opt option) {
5248 if opt != nil {
5349 opt(s)
5450 }
5551 }
5652
5753 func WithLogger(logger log.Logger) option {
58 return func(o *cwoptions) {
59 o.logger = logger
54 return func(c *CloudWatch) {
55 c.logger = logger
6056 }
6157 }
6258
6359 func WithPercentiles(p Percentiles) option {
64 return func(o *cwoptions) {
60 return func(c *CloudWatch) {
6561 validated := Percentiles{}
6662 for _, entry := range p {
6763 if entry.f < 0 || entry.f > 1 {
6965 }
7066 validated = append(validated, entry)
7167 }
72 o.percentiles = validated
68 c.percentiles = validated
7369 }
7470 }
7571
7672 func WithConcurrentRequests(n int) option {
77 return func(o *cwoptions) {
73 return func(c *CloudWatch) {
7874 if n > maxConcurrentRequests {
7975 n = maxConcurrentRequests
8076 }
81 o.numConcurrentRequests = n
77 c.numConcurrentRequests = n
8278 }
8379 }
8480
8783 // Callers must ensure that regular calls to Send are performed, either
8884 // manually or with one of the helper methods.
8985 func New(namespace string, svc cloudwatchiface.CloudWatchAPI, options ...option) *CloudWatch {
90 useOptions := &cwoptions{
86 cw := &CloudWatch{
87 sem: nil, // set below
88 namespace: namespace,
89 svc: svc,
90 counters: lv.NewSpace(),
91 gauges: lv.NewSpace(),
92 histograms: lv.NewSpace(),
9193 numConcurrentRequests: 10,
9294 logger: log.NewLogfmtLogger(os.Stderr),
9395 percentiles: Percentiles{
98100 },
99101 }
100102
101 for _, opt := range options {
102 useOptions.apply(opt)
103 }
104
105 return &CloudWatch{
106 sem: make(chan struct{}, useOptions.numConcurrentRequests),
107 namespace: namespace,
108 svc: svc,
109 counters: lv.NewSpace(),
110 gauges: lv.NewSpace(),
111 histograms: lv.NewSpace(),
112 cwoptions: useOptions,
113 }
103 for _, optFunc := range options {
104 optFunc(cw)
105 }
106
107 cw.sem = make(chan struct{}, cw.numConcurrentRequests)
108
109 return cw
114110 }
115111
116112 // NewCounter returns a counter. Observations are aggregated and emitted once