Skip to content

Commit

Permalink
Label http request handler tracing spans with the matched route name (#…
Browse files Browse the repository at this point in the history
…126)

* Pass options to tracing middleware

Signed-off-by: Goutham Veeramachaneni <[email protected]>

* Use the route matcher instead

Signed-off-by: Goutham Veeramachaneni <[email protected]>
  • Loading branch information
gouthamve authored and leth committed Oct 1, 2018
1 parent 2a0cb61 commit e017e7c
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
16 changes: 14 additions & 2 deletions middleware/http_tracing.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package middleware

import (
"fmt"
"net/http"

"github.com/opentracing-contrib/go-stdlib/nethttp"
Expand All @@ -10,11 +11,22 @@ import (
)

// Tracer is a middleware which traces incoming requests.
type Tracer struct{}
type Tracer struct {
RouteMatcher RouteMatcher
}

// Wrap implements Interface
func (t Tracer) Wrap(next http.Handler) http.Handler {
traceHandler := nethttp.Middleware(opentracing.GlobalTracer(), next)
opMatcher := nethttp.OperationNameFunc(func(r *http.Request) string {
op := getRouteName(t.RouteMatcher, r)
if op == "" {
return "HTTP " + r.Method
}

return fmt.Sprintf("HTTP %s - %s", r.Method, op)
})

traceHandler := nethttp.Middleware(opentracing.GlobalTracer(), next, opMatcher)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var maybeTracer http.Handler
// Don't try and trace websocket requests because nethttp.Middleware
Expand Down
14 changes: 12 additions & 2 deletions middleware/instrument.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,16 +64,26 @@ func (i Instrument) Wrap(next http.Handler) http.Handler {
// We do all this as we do not wish to emit high cardinality labels to
// prometheus.
func (i Instrument) getRouteName(r *http.Request) string {
route := getRouteName(i.RouteMatcher, r)
if route == "" {
route = "other"
}

return route
}

func getRouteName(routeMatcher RouteMatcher, r *http.Request) string {
var routeMatch mux.RouteMatch
if i.RouteMatcher != nil && i.RouteMatcher.Match(r, &routeMatch) {
if routeMatcher != nil && routeMatcher.Match(r, &routeMatch) {
if name := routeMatch.Route.GetName(); name != "" {
return name
}
if tmpl, err := routeMatch.Route.GetPathTemplate(); err == nil {
return MakeLabelValue(tmpl)
}
}
return "other"

return ""
}

var invalidChars = regexp.MustCompile(`[^a-zA-Z0-9]+`)
Expand Down
4 changes: 3 additions & 1 deletion server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,9 @@ func New(cfg Config) (*Server, error) {
RegisterInstrumentation(router)
}
httpMiddleware := []middleware.Interface{
middleware.Tracer{},
middleware.Tracer{
RouteMatcher: router,
},
middleware.Log{
Log: log,
},
Expand Down

0 comments on commit e017e7c

Please sign in to comment.