| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
// Based on https://github.com/DataDog/dd-trace-go/blob/8fb554ff7cf694267f9077ae35e27ce4689ed8b6/contrib/gin-gonic/gin/gintrace.go |
| 5 |
|
| 6 |
package otelgin // import "go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin" |
| 7 |
|
| 8 |
import ( |
| 9 |
"fmt" |
| 10 |
"time" |
| 11 |
|
| 12 |
"github.com/gin-gonic/gin" |
| 13 |
"go.opentelemetry.io/otel" |
| 14 |
"go.opentelemetry.io/otel/attribute" |
| 15 |
"go.opentelemetry.io/otel/codes" |
| 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/gin-gonic/gin/otelgin/internal/semconv" |
| 21 |
) |
| 22 |
|
| 23 |
const ( |
| 24 |
tracerKey = "otel-go-contrib-tracer" |
| 25 |
// ScopeName is the instrumentation scope name. |
| 26 |
ScopeName = "go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin" |
| 27 |
) |
| 28 |
|
| 29 |
// Middleware returns middleware that will trace incoming requests. |
| 30 |
// The service parameter should describe the name of the (virtual) |
| 31 |
// server handling the request. |
| 32 |
func Middleware(service string, opts ...Option) gin.HandlerFunc { |
| 33 |
cfg := config{} |
| 34 |
|
| 35 |
for _, opt := range opts { |
| 36 |
opt.apply(&cfg) |
| 37 |
} |
| 38 |
if cfg.TracerProvider == nil { |
| 39 |
cfg.TracerProvider = otel.GetTracerProvider() |
| 40 |
} |
| 41 |
tracer := cfg.TracerProvider.Tracer( |
| 42 |
ScopeName, |
| 43 |
oteltrace.WithInstrumentationVersion(Version), |
| 44 |
) |
| 45 |
if cfg.Propagators == nil { |
| 46 |
cfg.Propagators = otel.GetTextMapPropagator() |
| 47 |
} |
| 48 |
if cfg.MeterProvider == nil { |
| 49 |
cfg.MeterProvider = otel.GetMeterProvider() |
| 50 |
} |
| 51 |
if cfg.SpanNameFormatter == nil { |
| 52 |
cfg.SpanNameFormatter = defaultSpanNameFormatter |
| 53 |
} |
| 54 |
|
| 55 |
meter := cfg.MeterProvider.Meter( |
| 56 |
ScopeName, |
| 57 |
metric.WithInstrumentationVersion(Version), |
| 58 |
) |
| 59 |
|
| 60 |
sc := semconv.NewHTTPServer(meter) |
| 61 |
|
| 62 |
return func(c *gin.Context) { |
| 63 |
requestStartTime := time.Now() |
| 64 |
|
| 65 |
for _, f := range cfg.Filters { |
| 66 |
if !f(c.Request) { |
| 67 |
// Serve the request to the next middleware |
| 68 |
// if a filter rejects the request. |
| 69 |
c.Next() |
| 70 |
return |
| 71 |
} |
| 72 |
} |
| 73 |
for _, f := range cfg.GinFilters { |
| 74 |
if !f(c) { |
| 75 |
// Serve the request to the next middleware |
| 76 |
// if a filter rejects the request. |
| 77 |
c.Next() |
| 78 |
return |
| 79 |
} |
| 80 |
} |
| 81 |
c.Set(tracerKey, tracer) |
| 82 |
savedCtx := c.Request.Context() |
| 83 |
defer func() { |
| 84 |
c.Request = c.Request.WithContext(savedCtx) |
| 85 |
}() |
| 86 |
ctx := cfg.Propagators.Extract(savedCtx, propagation.HeaderCarrier(c.Request.Header)) |
| 87 |
|
| 88 |
requestTraceAttrOpts := semconv.RequestTraceAttrsOpts{ |
| 89 |
// Gin's ClientIP method can detect the client's IP from various headers set by proxies, and it's configurable |
| 90 |
HTTPClientIP: c.ClientIP(), |
| 91 |
} |
| 92 |
|
| 93 |
opts := []oteltrace.SpanStartOption{ |
| 94 |
oteltrace.WithAttributes(sc.RequestTraceAttrs(service, c.Request, requestTraceAttrOpts)...), |
| 95 |
oteltrace.WithAttributes(sc.Route(c.FullPath())), |
| 96 |
oteltrace.WithSpanKind(oteltrace.SpanKindServer), |
| 97 |
} |
| 98 |
|
| 99 |
opts = append(opts, cfg.SpanStartOptions...) |
| 100 |
|
| 101 |
spanName := cfg.SpanNameFormatter(c) |
| 102 |
if spanName == "" { |
| 103 |
spanName = fmt.Sprintf("HTTP %s route not found", c.Request.Method) |
| 104 |
} |
| 105 |
ctx, span := tracer.Start(ctx, spanName, opts...) |
| 106 |
defer span.End() |
| 107 |
|
| 108 |
// pass the span through the request context |
| 109 |
c.Request = c.Request.WithContext(ctx) |
| 110 |
|
| 111 |
// serve the request to the next middleware |
| 112 |
c.Next() |
| 113 |
|
| 114 |
status := c.Writer.Status() |
| 115 |
span.SetStatus(sc.Status(status)) |
| 116 |
span.SetAttributes(sc.ResponseTraceAttrs(semconv.ResponseTelemetry{ |
| 117 |
StatusCode: status, |
| 118 |
WriteBytes: int64(c.Writer.Size()), |
| 119 |
})...) |
| 120 |
|
| 121 |
if len(c.Errors) > 0 { |
| 122 |
span.SetStatus(codes.Error, c.Errors.String()) |
| 123 |
for _, err := range c.Errors { |
| 124 |
span.RecordError(err.Err) //nolint:forbidigo // TODO: https://github.com/open-telemetry/opentelemetry-go-contrib/issues/8441 |
| 125 |
} |
| 126 |
} |
| 127 |
|
| 128 |
// Record the server-side attributes. |
| 129 |
var additionalAttributes []attribute.KeyValue |
| 130 |
if cfg.MetricAttributeFn != nil { |
| 131 |
additionalAttributes = append(additionalAttributes, cfg.MetricAttributeFn(c.Request)...) |
| 132 |
} |
| 133 |
if cfg.GinMetricAttributeFn != nil { |
| 134 |
additionalAttributes = append(additionalAttributes, cfg.GinMetricAttributeFn(c)...) |
| 135 |
} |
| 136 |
|
| 137 |
sc.RecordMetrics(ctx, semconv.ServerMetricData{ |
| 138 |
ServerName: service, |
| 139 |
ResponseSize: int64(c.Writer.Size()), |
| 140 |
MetricAttributes: semconv.MetricAttributes{ |
| 141 |
Req: c.Request, |
| 142 |
StatusCode: status, |
| 143 |
Route: c.FullPath(), |
| 144 |
AdditionalAttributes: additionalAttributes, |
| 145 |
}, |
| 146 |
MetricData: semconv.MetricData{ |
| 147 |
RequestSize: c.Request.ContentLength, |
| 148 |
RequestDuration: time.Since(requestStartTime), |
| 149 |
}, |
| 150 |
}) |
| 151 |
} |
| 152 |
} |
| 153 |
|
| 154 |
// HTML will trace the rendering of the template as a child of the |
| 155 |
// span in the given context. This is a replacement for |
| 156 |
// gin.Context.HTML function - it invokes the original function after |
| 157 |
// setting up the span. |
| 158 |
func HTML(c *gin.Context, code int, name string, obj any) { |
| 159 |
var tracer oteltrace.Tracer |
| 160 |
tracerInterface, ok := c.Get(tracerKey) |
| 161 |
if ok { |
| 162 |
tracer, ok = tracerInterface.(oteltrace.Tracer) |
| 163 |
} |
| 164 |
if !ok { |
| 165 |
tracer = otel.GetTracerProvider().Tracer( |
| 166 |
ScopeName, |
| 167 |
oteltrace.WithInstrumentationVersion(Version), |
| 168 |
) |
| 169 |
} |
| 170 |
savedContext := c.Request.Context() |
| 171 |
defer func() { |
| 172 |
c.Request = c.Request.WithContext(savedContext) |
| 173 |
}() |
| 174 |
opt := oteltrace.WithAttributes(attribute.String("go.template", name)) |
| 175 |
_, span := tracer.Start(savedContext, "gin.renderer.html", opt) |
| 176 |
defer span.End() |
| 177 |
c.HTML(code, name, obj) |
| 178 |
} |