request_tracing.go 871 B

123456789101112131415161718192021222324252627282930313233
  1. package middleware
  2. import (
  3. "fmt"
  4. "net/http"
  5. opentracing "github.com/opentracing/opentracing-go"
  6. "github.com/opentracing/opentracing-go/ext"
  7. "gopkg.in/macaron.v1"
  8. )
  9. func RequestTracing(handler string) macaron.Handler {
  10. return func(res http.ResponseWriter, req *http.Request, c *macaron.Context) {
  11. rw := res.(macaron.ResponseWriter)
  12. tracer := opentracing.GlobalTracer()
  13. wireContext, _ := tracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header))
  14. span := tracer.StartSpan(fmt.Sprintf("HTTP %s", handler), ext.RPCServerOption(wireContext))
  15. defer span.Finish()
  16. ctx := opentracing.ContextWithSpan(req.Context(), span)
  17. c.Req.Request = req.WithContext(ctx)
  18. c.Next()
  19. status := rw.Status()
  20. ext.HTTPStatusCode.Set(span, uint16(status))
  21. ext.HTTPUrl.Set(span, req.RequestURI)
  22. ext.HTTPMethod.Set(span, req.Method)
  23. }
  24. }