request_tracing.go 925 Bytes
Newer Older
1 2 3
package middleware

import (
4
	"fmt"
5 6 7
	"net/http"

	opentracing "github.com/opentracing/opentracing-go"
8
	"github.com/opentracing/opentracing-go/ext"
9 10 11 12

	"gopkg.in/macaron.v1"
)

bergquist committed
13
func RequestTracing(handler string) macaron.Handler {
14 15 16
	return func(res http.ResponseWriter, req *http.Request, c *macaron.Context) {
		rw := res.(macaron.ResponseWriter)

17 18
		tracer := opentracing.GlobalTracer()
		wireContext, _ := tracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header))
19
		span := tracer.StartSpan(fmt.Sprintf("HTTP %s", handler), ext.RPCServerOption(wireContext))
20 21 22
		defer span.Finish()

		ctx := opentracing.ContextWithSpan(req.Context(), span)
23
		c.Req.Request = req.WithContext(ctx)
24 25 26 27 28

		c.Next()

		status := rw.Status()

29 30 31
		ext.HTTPStatusCode.Set(span, uint16(status))
		ext.HTTPUrl.Set(span, req.RequestURI)
		ext.HTTPMethod.Set(span, req.Method)
32 33 34
		if status >= 400 {
			ext.Error.Set(span, true)
		}
35 36
	}
}