Repository navigation
Expand file tree
/
Copy pathtracer.go
More file actions
93 lines (68 loc) · 1.77 KB
/
Copy pathtracer.go
File metadata and controls
93 lines (68 loc) · 1.77 KB
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
package main
import (
"context"
"fmt"
"log"
"net/http"
pb "portpulse/proto"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type Tracer struct{
conn *grpc.ClientConn
client pb.TelemetryCollectorClient
}
type statusRecorder struct{
http.ResponseWriter
statusCode int
}
func (rec *statusRecorder) WriteHeader(code int){
rec.statusCode = code
rec.ResponseWriter.WriteHeader(code)
}
func NewTracer(target string) (*Tracer , error){
conn,err:= grpc.NewClient(
target,
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil{
return nil, fmt.Errorf("failed to connect to TracePulse: %w", err)
}
client:= pb.NewTelemetryCollectorClient(conn)
return &Tracer{
conn:conn,
client:client,
},nil
}
func (t *Tracer) Middleware(next http.Handler) http.Handler{
return http.HandlerFunc(func(w http.ResponseWriter , r *http.Request){
start:= time.Now()
rec:= &statusRecorder{
ResponseWriter: w,
statusCode: http.StatusOK,
}
next.ServeHTTP(rec,r)
duration:= time.Since(start).Milliseconds()
span:= &pb.Span{
TraceId: fmt.Sprintf("trace-%d", time.Now().UnixNano()),
SpanId: fmt.Sprintf("span-%d", time.Now().UnixNano()%1000000),
ServiceName: "portpulse-gateway",
OperationName: fmt.Sprintf("%s %s", r.Method, r.URL.Path),
StatusCode: fmt.Sprintf("%d", rec.statusCode),
DurationMs: duration,
}
go func (s *pb.Span) {
ctx,cancel:= context.WithTimeout(context.Background(),2*time.Second)
defer cancel()
_,err:= t.client.IngestSpans(ctx,&pb.IngestReqest{Spans: []*pb.Span{s}})
if err != nil{
log.Printf("[tracer] failed to ship span to TracePulse: %v", err)
return
}
}(span)
})
}
func (t *Tracer) Close() error{
return t.conn.Close()
}