Debian Codegraph @

instrumentation/github.com/labstack/echo/otelecho/echo.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package otelecho // import "go.opentelemetry.io/contrib/instrumentation/github.com/labstack/echo/otelecho"
5
6 import (
7 "net/http"
8 "slices"
9 "strings"
10 "time"
11
12 "github.com/labstack/echo/v4"
13 "github.com/labstack/echo/v4/middleware"
14 "go.opentelemetry.io/otel"
15 "go.opentelemetry.io/otel/attribute"
16 "go.opentelemetry.io/otel/metric"
17 "go.opentelemetry.io/otel/propagation"
18 oteltrace "go.opentelemetry.io/otel/trace"
19
20 "go.opentelemetry.io/contrib/instrumentation/github.com/labstack/echo/otelecho/internal/semconv"
21 )
22
23 const (
24 tracerKey = "otel-go-contrib-tracer-labstack-echo"
25 // ScopeName is the instrumentation scope name.
26 ScopeName = "go.opentelemetry.io/contrib/instrumentation/github.com/labstack/echo/otelecho"
27 )
28
29 // Middleware returns echo middleware which will trace incoming requests.
30 func Middleware(serverName string, opts ...Option) echo.MiddlewareFunc {
31 cfg := config{}
32 for _, opt := range opts {
33 opt.apply(&cfg)
34 }
35 if cfg.TracerProvider == nil {
36 cfg.TracerProvider = otel.GetTracerProvider()
37 }
38 tracer := cfg.TracerProvider.Tracer(
39 ScopeName,
40 oteltrace.WithInstrumentationVersion(Version),
41 )
42 if cfg.Propagators == nil {
43 cfg.Propagators = otel.GetTextMapPropagator()
44 }
45 if cfg.MeterProvider == nil {
46 cfg.MeterProvider = otel.GetMeterProvider()
47 }
48 if cfg.Skipper == nil {
49 cfg.Skipper = middleware.DefaultSkipper
50 }
51 if cfg.OnError == nil {
52 cfg.OnError = defaultOnError
53 }
54
55 meter := cfg.MeterProvider.Meter(
56 ScopeName,
57 metric.WithInstrumentationVersion(Version),
58 )
59
60 semconvSrv := semconv.NewHTTPServer(meter)
61
62 return func(next echo.HandlerFunc) echo.HandlerFunc {
63 return func(c echo.Context) error {
64 requestStartTime := time.Now()
65 if cfg.Skipper(c) {
66 return next(c)
67 }
68
69 c.Set(tracerKey, tracer)
70 request := c.Request()
71 savedCtx := request.Context()
72 defer func() {
73 request = request.WithContext(savedCtx)
74 c.SetRequest(request)
75 }()
76 ctx := cfg.Propagators.Extract(savedCtx, propagation.HeaderCarrier(request.Header))
77 opts := []oteltrace.SpanStartOption{
78 oteltrace.WithAttributes(
79 semconvSrv.RequestTraceAttrs(serverName, request, semconv.RequestTraceAttrsOpts{})...,
80 ),
81 oteltrace.WithSpanKind(oteltrace.SpanKindServer),
82 }
83 if path := c.Path(); path != "" {
84 rAttr := semconvSrv.Route(path)
85 opts = append(opts, oteltrace.WithAttributes(rAttr))
86 }
87 spanName := spanNameFormatter(c)
88
89 ctx, span := tracer.Start(ctx, spanName, opts...)
90 defer span.End()
91
92 // pass the span through the request context
93 c.SetRequest(request.WithContext(ctx))
94
95 // serve the request to the next middleware
96 err := next(c)
97 if err != nil {
98 span.SetAttributes(attribute.String("echo.error", err.Error()))
99 cfg.OnError(c, err)
100 }
101
102 status := c.Response().Status
103 span.SetStatus(semconvSrv.Status(status))
104 span.SetAttributes(semconvSrv.ResponseTraceAttrs(semconv.ResponseTelemetry{
105 StatusCode: status,
106 WriteBytes: c.Response().Size,
107 })...)
108
109 // Record the server-side attributes.
110 var additionalAttributes []attribute.KeyValue
111 if cfg.MetricAttributeFn != nil {
112 additionalAttributes = append(additionalAttributes, cfg.MetricAttributeFn(request)...)
113 }
114 if cfg.EchoMetricAttributeFn != nil {
115 additionalAttributes = append(additionalAttributes, cfg.EchoMetricAttributeFn(c)...)
116 }
117
118 semconvSrv.RecordMetrics(ctx, semconv.ServerMetricData{
119 ServerName: serverName,
120 ResponseSize: c.Response().Size,
121 MetricAttributes: semconv.MetricAttributes{
122 Req: request,
123 StatusCode: status,
124 Route: c.Path(),
125 AdditionalAttributes: additionalAttributes,
126 },
127 MetricData: semconv.MetricData{
128 RequestSize: request.ContentLength,
129 RequestDuration: time.Since(requestStartTime),
130 },
131 })
132
133 return err
134 }
135 }
136 }
137
138 func spanNameFormatter(c echo.Context) string {
139 method, path := strings.ToUpper(c.Request().Method), c.Path()
140 if !slices.Contains([]string{
141 http.MethodGet, http.MethodHead,
142 http.MethodPost, http.MethodPut,
143 http.MethodPatch, http.MethodDelete,
144 http.MethodConnect, http.MethodOptions,
145 http.MethodTrace,
146 }, method) {
147 method = "HTTP"
148 }
149
150 if path != "" {
151 return method + " " + path
152 }
153
154 return method
155 }