forked from labstack/echo-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathecho.go
More file actions
186 lines (163 loc) · 4.99 KB
/
Copy pathecho.go
File metadata and controls
186 lines (163 loc) · 4.99 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
package otelecho
import (
"errors"
"net/http"
"slices"
"strings"
"time"
"github.com/labstack/echo-contrib/otelecho/v5/internal/semconv"
"github.com/labstack/echo/v5"
"github.com/labstack/echo/v5/middleware"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/propagation"
oteltrace "go.opentelemetry.io/otel/trace"
)
const (
tracerKey = "labstack-echo-otelecho-tracer"
// ScopeName is the instrumentation scope name.
ScopeName = "github.com/labstack/echo-contrib/otelecho"
)
// Middleware returns echo middleware which will trace incoming requests.
func Middleware(serverName string, opts ...Option) echo.MiddlewareFunc {
cfg := config{}
for _, opt := range opts {
opt.apply(&cfg)
}
if cfg.TracerProvider == nil {
cfg.TracerProvider = otel.GetTracerProvider()
}
tracer := cfg.TracerProvider.Tracer(
ScopeName,
oteltrace.WithInstrumentationVersion(Version),
)
if cfg.Propagators == nil {
cfg.Propagators = otel.GetTextMapPropagator()
}
if cfg.MeterProvider == nil {
cfg.MeterProvider = otel.GetMeterProvider()
}
if cfg.Skipper == nil {
cfg.Skipper = middleware.DefaultSkipper
}
if cfg.OnError == nil {
cfg.OnError = defaultOnError
}
meter := cfg.MeterProvider.Meter(
ScopeName,
metric.WithInstrumentationVersion(Version),
)
semconvSrv := semconv.NewHTTPServer(meter)
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
if cfg.Skipper(c) {
return next(c)
}
requestStartTime := time.Now()
c.Set(tracerKey, tracer)
request := c.Request()
savedCtx := request.Context()
defer func() {
request = request.WithContext(savedCtx)
c.SetRequest(request)
}()
ctx := cfg.Propagators.Extract(savedCtx, propagation.HeaderCarrier(request.Header))
opts := []oteltrace.SpanStartOption{
oteltrace.WithAttributes(
semconvSrv.RequestTraceAttrs(serverName, request, semconv.RequestTraceAttrsOpts{})...,
),
oteltrace.WithSpanKind(oteltrace.SpanKindServer),
}
if path := c.Path(); path != "" {
rAttr := semconvSrv.Route(path)
opts = append(opts, oteltrace.WithAttributes(rAttr))
}
spanName := spanNameFormatter(c)
ctx, span := tracer.Start(ctx, spanName, opts...)
defer span.End()
// pass the span through the request context
c.SetRequest(request.WithContext(ctx))
// serve the request to the next middleware
err := next(c)
if err != nil {
span.SetAttributes(attribute.String("echo.error", err.Error()))
cfg.OnError(c, err)
}
// Get the response to access Status and Size after the handler chain completes
resp, _ := echo.UnwrapResponse(c.Response())
// Determine status code
// In Echo v5, when there's an error, the HTTPErrorHandler hasn't written the response yet,
// so we need to determine the status from the error itself
var status int
var responseSize int64
if err != nil {
// Determine status from error
// First try errors.As for wrapped HTTPError
var he *echo.HTTPError
if errors.As(err, &he) {
status = he.Code
} else {
// Fallback to Internal Server Error
status = http.StatusInternalServerError
}
} else if resp != nil {
// No error, use the response status
status = resp.Status
responseSize = resp.Size
} else {
status = http.StatusOK
}
// Get response size if not already set
if responseSize == 0 && resp != nil {
responseSize = resp.Size
}
span.SetStatus(semconvSrv.Status(status))
span.SetAttributes(semconvSrv.ResponseTraceAttrs(semconv.ResponseTelemetry{
StatusCode: status,
WriteBytes: responseSize,
})...)
// Record the server-side attributes.
var additionalAttributes []attribute.KeyValue
if path := c.Path(); path != "" {
additionalAttributes = append(additionalAttributes, semconvSrv.Route(path))
}
if cfg.MetricAttributeFn != nil {
additionalAttributes = append(additionalAttributes, cfg.MetricAttributeFn(request)...)
}
if cfg.EchoMetricAttributeFn != nil {
additionalAttributes = append(additionalAttributes, cfg.EchoMetricAttributeFn(c)...)
}
semconvSrv.RecordMetrics(ctx, semconv.ServerMetricData{
ServerName: serverName,
ResponseSize: responseSize,
MetricAttributes: semconv.MetricAttributes{
Req: request,
StatusCode: status,
AdditionalAttributes: additionalAttributes,
},
MetricData: semconv.MetricData{
RequestSize: request.ContentLength,
ElapsedTime: float64(time.Since(requestStartTime)) / float64(time.Millisecond),
},
})
return err
}
}
}
func spanNameFormatter(c *echo.Context) string {
method, path := strings.ToUpper(c.Request().Method), c.Path()
if !slices.Contains([]string{
http.MethodGet, http.MethodPost,
http.MethodPut, http.MethodDelete,
http.MethodHead, http.MethodPatch,
http.MethodConnect, http.MethodOptions,
http.MethodTrace,
}, method) {
method = "HTTP"
}
if path != "" {
return method + " " + path
}
return method
}