-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
instrument.go
70 lines (56 loc) · 1.88 KB
/
instrument.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
package queryrange
import (
"context"
"strconv"
"time"
"github.com/grafana/dskit/httpgrpc"
"github.com/grafana/dskit/instrument"
"github.com/grafana/dskit/middleware"
"github.com/opentracing/opentracing-go"
"github.com/grafana/dskit/server"
"github.com/grafana/loki/v3/pkg/querier/queryrange/queryrangebase"
)
const (
method = "GET"
)
type Instrument struct {
*server.Metrics
}
var _ queryrangebase.Middleware = Instrument{}
// Wrap implements the queryrangebase.Middleware
func (i Instrument) Wrap(next queryrangebase.Handler) queryrangebase.Handler {
return queryrangebase.HandlerFunc(func(ctx context.Context, r queryrangebase.Request) (queryrangebase.Response, error) {
route := DefaultCodec.Path(r)
route = middleware.MakeLabelValue(route)
inflight := i.InflightRequests.WithLabelValues(method, route)
inflight.Inc()
defer inflight.Dec()
begin := time.Now()
result, err := next.Do(ctx, r)
i.observe(ctx, route, err, time.Since(begin))
return result, err
})
}
func (i Instrument) observe(ctx context.Context, route string, err error, duration time.Duration) {
respStatus := "200"
if err != nil {
if errResp, ok := httpgrpc.HTTPResponseFromError(err); ok {
respStatus = strconv.Itoa(int(errResp.Code))
} else {
respStatus = "500"
}
}
instrument.ObserveWithExemplar(ctx, i.RequestDuration.WithLabelValues(method, route, respStatus, "false"), duration.Seconds())
}
type Tracer struct{}
var _ queryrangebase.Middleware = Tracer{}
// Wrap implements the queryrangebase.Middleware
func (t Tracer) Wrap(next queryrangebase.Handler) queryrangebase.Handler {
return queryrangebase.HandlerFunc(func(ctx context.Context, r queryrangebase.Request) (queryrangebase.Response, error) {
route := DefaultCodec.Path(r)
route = middleware.MakeLabelValue(route)
span, ctx := opentracing.StartSpanFromContext(ctx, route)
defer span.Finish()
return next.Do(ctx, r)
})
}