...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package stats
17
18 import (
19 "context"
20
21 "go.opencensus.io/metric/metricdata"
22 "go.opencensus.io/stats/internal"
23 "go.opencensus.io/tag"
24 )
25
26 func init() {
27 internal.SubscriptionReporter = func(measure string) {
28 mu.Lock()
29 measures[measure].subscribe()
30 mu.Unlock()
31 }
32 }
33
34
35
36 type Recorder interface {
37
38
39 Record(*tag.Map, interface{}, map[string]interface{})
40 }
41
42 type recordOptions struct {
43 attachments metricdata.Attachments
44 mutators []tag.Mutator
45 measurements []Measurement
46 recorder Recorder
47 }
48
49
50 func WithAttachments(attachments metricdata.Attachments) Options {
51 return func(ro *recordOptions) {
52 ro.attachments = attachments
53 }
54 }
55
56
57 func WithTags(mutators ...tag.Mutator) Options {
58 return func(ro *recordOptions) {
59 ro.mutators = mutators
60 }
61 }
62
63
64 func WithMeasurements(measurements ...Measurement) Options {
65 return func(ro *recordOptions) {
66 ro.measurements = measurements
67 }
68 }
69
70
71
72 func WithRecorder(meter Recorder) Options {
73 return func(ro *recordOptions) {
74 ro.recorder = meter
75 }
76 }
77
78
79 type Options func(*recordOptions)
80
81 func createRecordOption(ros ...Options) *recordOptions {
82 o := &recordOptions{}
83 for _, ro := range ros {
84 ro(o)
85 }
86 return o
87 }
88
89 type measurementRecorder = func(tags *tag.Map, measurement []Measurement, attachments map[string]interface{})
90
91
92
93 func Record(ctx context.Context, ms ...Measurement) {
94
95
96 if len(ms) == 0 {
97 return
98 }
99 recorder := internal.MeasurementRecorder.(measurementRecorder)
100 record := false
101 for _, m := range ms {
102 if m.desc.subscribed() {
103 record = true
104 break
105 }
106 }
107 if !record {
108 return
109 }
110 recorder(tag.FromContext(ctx), ms, nil)
111 return
112 }
113
114
115
116
117
118
119 func RecordWithTags(ctx context.Context, mutators []tag.Mutator, ms ...Measurement) error {
120 return RecordWithOptions(ctx, WithTags(mutators...), WithMeasurements(ms...))
121 }
122
123
124
125
126 func RecordWithOptions(ctx context.Context, ros ...Options) error {
127 o := createRecordOption(ros...)
128 if len(o.measurements) == 0 {
129 return nil
130 }
131 recorder := internal.DefaultRecorder
132 if o.recorder != nil {
133 recorder = o.recorder.Record
134 }
135 if recorder == nil {
136 return nil
137 }
138 record := false
139 for _, m := range o.measurements {
140 if m.desc.subscribed() {
141 record = true
142 break
143 }
144 }
145 if !record {
146 return nil
147 }
148 if len(o.mutators) > 0 {
149 var err error
150 if ctx, err = tag.New(ctx, o.mutators...); err != nil {
151 return err
152 }
153 }
154 recorder(tag.FromContext(ctx), o.measurements, o.attachments)
155 return nil
156 }
157
View as plain text