forked from DataDog/dd-trace-go
/
echotrace.go
64 lines (55 loc) · 1.92 KB
/
echotrace.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
57
58
59
60
61
62
63
64
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-2020 Datadog, Inc.
// Package echo provides functions to trace the labstack/echo package (https://github.com/labstack/echo).
package echo
import (
"math"
"strconv"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
"github.com/labstack/echo"
)
// Middleware returns echo middleware which will trace incoming requests.
func Middleware(opts ...Option) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
cfg := new(config)
defaults(cfg)
for _, fn := range opts {
fn(cfg)
}
return func(c echo.Context) error {
request := c.Request()
resource := request.Method + " " + c.Path()
opts := []ddtrace.StartSpanOption{
tracer.ServiceName(cfg.serviceName),
tracer.ResourceName(resource),
tracer.SpanType(ext.SpanTypeWeb),
tracer.Tag(ext.HTTPMethod, request.Method),
tracer.Tag(ext.HTTPURL, request.URL.Path),
tracer.Measured(),
}
if !math.IsNaN(cfg.analyticsRate) {
opts = append(opts, tracer.Tag(ext.EventSampleRate, cfg.analyticsRate))
}
if spanctx, err := tracer.Extract(tracer.HTTPHeadersCarrier(request.Header)); err == nil {
opts = append(opts, tracer.ChildOf(spanctx))
}
span, ctx := tracer.StartSpanFromContext(request.Context(), "http.request", opts...)
defer span.Finish()
// 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.SetTag(ext.Error, err)
// invokes the registered HTTP error handler
c.Error(err)
}
span.SetTag(ext.HTTPCode, strconv.Itoa(c.Response().Status))
return err
}
}
}