forked from Equanox/petasos-rewriter
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmiddleware.go
41 lines (36 loc) · 1.4 KB
/
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
package main
import (
"github.com/getsentry/sentry-go"
"github.com/labstack/echo/v4"
"github.com/rs/zerolog/log"
"go.opentelemetry.io/otel/trace"
)
// Middleware returns echo middleware which will inject
// SpanID and TraceID in response headers, will be creating
// context based logger and will be injecting trace information
// in sentry scope
func Middleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
req := c.Request()
ctx := req.Context()
rsc := trace.RemoteSpanContextFromContext(ctx)
span := trace.SpanFromContext(ctx)
spanId, traceId := span.SpanContext().SpanID().String(), span.SpanContext().TraceID().String()
if !rsc.IsValid() && span.SpanContext().IsValid() {
c.Response().Header().Set(spanIdHeader, spanId)
c.Response().Header().Set(traceIdHeader, traceId)
}
// Creating context based loggger
logger := log.With().Str(traceIdHeader, traceId).Str(spanIdHeader, spanId).Logger()
ctx = logger.WithContext(ctx)
request := req.WithContext(ctx)
c.SetRequest(request)
// Adding trace information in sentry scope.
sentry.ConfigureScope(func(scope *sentry.Scope) {
scope.SetExtras(map[string]interface{}{"span_id": spanId, "trace_id": traceId, "X-TENANT-ID": req.Header.Get("X-TENANT-ID"), "X-Webpa-Device-Name": req.Header.Get("X-Webpa-Device-Name")})
})
return next(c)
}
}
}