-
Notifications
You must be signed in to change notification settings - Fork 427
/
Copy pathtrace_mw.go
executable file
·84 lines (68 loc) · 1.85 KB
/
trace_mw.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
package main
import (
"fmt"
"net/http"
"google.golang.org/api/option"
"golang.org/x/net/context"
"cloud.google.com/go/trace"
"github.com/Sirupsen/logrus"
"v2.staffjoy.com/environments"
)
const (
testRate = 1.0 // 100%
testLimit = 100 // Max 100 req/s
)
var (
projectID string
)
func init() {
projectID = environments.GetGoogleCloudProject()
}
// TraceMiddleware is a negroni middleware that reports URL timing to
// Google Cloud
type TraceMiddleware struct {
Logger *logrus.Entry
Config environments.Config
TraceClient *trace.Client
}
// NewTraceMiddleware returns a new middleware for traces
func NewTraceMiddleware(logger *logrus.Entry, config environments.Config) (*TraceMiddleware, error) {
var traceClient *trace.Client
if !config.Debug {
var err error
traceClient, err = trace.NewClient(context.Background(), projectID, option.WithServiceAccountFile(environments.GoogleCloudSecretPath))
if err != nil {
return nil, fmt.Errorf("Unable to initialize trace client - %v", err)
}
policy, err := trace.NewLimitedSampler(testRate, testLimit)
if err != nil {
return nil, fmt.Errorf("Unable to initialize trace client - %v", err)
}
traceClient.SetSamplingPolicy(policy)
}
logger.Infof("trace client init %v", traceClient)
return &TraceMiddleware{
Logger: logger.WithFields(logrus.Fields{
"middleware": "TraceMiddleware",
}),
Config: config,
TraceClient: traceClient,
}, nil
}
func (svc *TraceMiddleware) ServeHTTP(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
var span *trace.Span
if !svc.Config.Debug {
// Start trace
span = svc.TraceClient.SpanFromRequest(req)
}
next(res, req)
if !svc.Config.Debug {
// Finish trace
go func(span *trace.Span) {
err := span.FinishWait()
if err != nil {
svc.Logger.Warningf("Could not finish trace - %v", err)
}
}(span)
}
}