-
Notifications
You must be signed in to change notification settings - Fork 67
/
tracing_middleware.go
56 lines (47 loc) · 1.34 KB
/
tracing_middleware.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
package util
import (
"context"
"github.com/labstack/echo/v4"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
"go.opentelemetry.io/otel/trace"
)
func TracingMiddleware(tcr trace.Tracer) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
r := c.Request()
attrs := []attribute.KeyValue{
semconv.HTTPMethodKey.String(r.Method),
semconv.HTTPRouteKey.String(r.URL.Path),
semconv.HTTPClientIPKey.String(r.RemoteAddr),
semconv.HTTPRequestContentLengthKey.Int64(c.Request().ContentLength),
}
if reqid := r.Header.Get("EstClientReqID"); reqid != "" {
if len(reqid) > 64 {
reqid = reqid[:64]
}
attrs = append(attrs, attribute.String("ClientReqID", reqid))
}
tctx, span := tcr.Start(context.Background(),
"HTTP "+r.Method+" "+c.Path(),
trace.WithAttributes(attrs...),
)
defer span.End()
r = r.WithContext(tctx)
c.SetRequest(r)
err := next(c)
if err != nil {
span.SetStatus(codes.Error, err.Error())
span.RecordError(err)
} else {
span.SetStatus(codes.Ok, "")
}
span.SetAttributes(
semconv.HTTPStatusCodeKey.Int(c.Response().Status),
semconv.HTTPResponseContentLengthKey.Int64(c.Response().Size),
)
return err
}
}
}