forked from slok/go-http-metrics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopencensus.go
215 lines (182 loc) · 5.87 KB
/
opencensus.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package opencensus
import (
"context"
"time"
"go.opencensus.io/stats"
"go.opencensus.io/stats/view"
"go.opencensus.io/tag"
"github.com/slok/go-http-metrics/metrics"
)
var (
durationBuckets = []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10}
sizeBuckets = []float64{100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000}
)
// Config has the dependencies and values of the recorder.
type Config struct {
// DurationBuckets are the buckets used for the HTTP request duration metrics,
// by default uses default buckets (from 5ms to 10s).
DurationBuckets []float64
// SizeBuckets are the buckets for the HTTP response size metrics,
// by default uses a exponential buckets from 100B to 1GB.
SizeBuckets []float64
// HandlerIDLabel is the name that will be set to the handler ID label, by default is `handler`.
HandlerIDLabel string
// StatusCodeLabel is the name that will be set to the status code label, by default is `code`.
StatusCodeLabel string
// MethodLabel is the name that will be set to the method label, by default is `method`.
MethodLabel string
// ServiceLabel is the name that will be set to the service label, by default is `service`.
ServiceLabel string
// UnregisterViewsBeforeRegister will unregister the previous Recorder views before registering
// again. This is required on cases where multiple instances of recorder will be made due to how
// Opencensus is implemented (everything is at global state). Sadly this option is a kind of hack
// so we can test without exposing the views to the user. On regular usage this option is very
// rare to use it.
UnregisterViewsBeforeRegister bool
}
func (c *Config) defaults() {
if len(c.DurationBuckets) == 0 {
c.DurationBuckets = durationBuckets
}
if len(c.SizeBuckets) == 0 {
c.SizeBuckets = sizeBuckets
}
if c.HandlerIDLabel == "" {
c.HandlerIDLabel = "handler"
}
if c.StatusCodeLabel == "" {
c.StatusCodeLabel = "code"
}
if c.MethodLabel == "" {
c.MethodLabel = "method"
}
if c.ServiceLabel == "" {
c.ServiceLabel = "service"
}
}
type recorder struct {
// Keys.
codeKey tag.Key
methodKey tag.Key
handlerKey tag.Key
serviceKey tag.Key
// Measures.
latencySecs *stats.Float64Measure
sizeBytes *stats.Int64Measure
inflightCount *stats.Int64Measure
}
// NewRecorder returns a new Recorder that uses OpenCensus stats
// as the backend.
func NewRecorder(cfg Config) (metrics.Recorder, error) {
cfg.defaults()
r := &recorder{}
// Prepare metrics.
err := r.createKeys(cfg)
if err != nil {
return nil, err
}
r.createMeasurements()
err = r.registerViews(cfg)
if err != nil {
return nil, err
}
return r, nil
}
func (r *recorder) createKeys(cfg Config) error {
code, err := tag.NewKey(cfg.StatusCodeLabel)
if err != nil {
return err
}
r.codeKey = code
method, err := tag.NewKey(cfg.MethodLabel)
if err != nil {
return err
}
r.methodKey = method
handler, err := tag.NewKey(cfg.HandlerIDLabel)
if err != nil {
return err
}
r.handlerKey = handler
service, err := tag.NewKey(cfg.ServiceLabel)
if err != nil {
return err
}
r.serviceKey = service
return nil
}
func (r *recorder) createMeasurements() {
r.latencySecs = stats.Float64(
"http_request_duration_seconds",
"The latency of the HTTP requests",
"s")
r.sizeBytes = stats.Int64(
"http_response_size_bytes",
"The size of the HTTP responses",
stats.UnitBytes)
r.inflightCount = stats.Int64(
"http_requests_inflight",
"The number of inflight requests being handled at the same time",
stats.UnitNone)
}
func (r recorder) registerViews(cfg Config) error {
// OpenCensus uses global states, sadly we can't have view instance.
durationView := &view.View{
Name: "http_request_duration_seconds",
Description: "The latency of the HTTP requests",
TagKeys: []tag.Key{r.serviceKey, r.handlerKey, r.methodKey, r.codeKey},
Measure: r.latencySecs,
Aggregation: view.Distribution(cfg.DurationBuckets...),
}
sizeView := &view.View{
Name: "http_response_size_bytes",
Description: "The size of the HTTP responses",
TagKeys: []tag.Key{r.serviceKey, r.handlerKey, r.methodKey, r.codeKey},
Measure: r.sizeBytes,
Aggregation: view.Distribution(cfg.SizeBuckets...),
}
inflightView := &view.View{
Name: "http_requests_inflight",
Description: "The number of inflight requests being handled at the same time",
TagKeys: []tag.Key{r.serviceKey, r.handlerKey},
Measure: r.inflightCount,
Aggregation: view.Sum(),
}
// Do we need to unregister the same views before registering.
if cfg.UnregisterViewsBeforeRegister {
view.Unregister(durationView, sizeView, inflightView)
}
err := view.Register(durationView, sizeView, inflightView)
if err != nil {
return err
}
return nil
}
func (r recorder) ObserveHTTPRequestDuration(ctx context.Context, p metrics.HTTPReqProperties, duration time.Duration) {
ctx = r.ctxWithTagFromHTTPReqProperties(ctx, p)
stats.Record(ctx, r.latencySecs.M(duration.Seconds()))
}
func (r recorder) ObserveHTTPResponseSize(ctx context.Context, p metrics.HTTPReqProperties, sizeBytes int64) {
ctx = r.ctxWithTagFromHTTPReqProperties(ctx, p)
stats.Record(ctx, r.sizeBytes.M(sizeBytes))
}
func (r recorder) AddInflightRequests(ctx context.Context, p metrics.HTTPProperties, quantity int) {
ctx = r.ctxWithTagFromHTTPProperties(ctx, p)
stats.Record(ctx, r.inflightCount.M(int64(quantity)))
}
func (r recorder) ctxWithTagFromHTTPReqProperties(ctx context.Context, p metrics.HTTPReqProperties) context.Context {
newCtx, _ := tag.New(ctx,
tag.Upsert(r.serviceKey, p.Service),
tag.Upsert(r.handlerKey, p.ID),
tag.Upsert(r.methodKey, p.Method),
tag.Upsert(r.codeKey, p.Code),
)
return newCtx
}
func (r recorder) ctxWithTagFromHTTPProperties(ctx context.Context, p metrics.HTTPProperties) context.Context {
newCtx, _ := tag.New(ctx,
tag.Upsert(r.serviceKey, p.Service),
tag.Upsert(r.handlerKey, p.ID),
)
return newCtx
}