Skip to content

Commit

Permalink
Print traceID with request
Browse files Browse the repository at this point in the history
Signed-off-by: Goutham Veeramachaneni <[email protected]>
  • Loading branch information
gouthamve committed Aug 28, 2018
1 parent d442d08 commit d906d37
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
16 changes: 16 additions & 0 deletions middleware/http_tracing.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import (

"github.com/opentracing-contrib/go-stdlib/nethttp"
"github.com/opentracing/opentracing-go"
ot "github.com/opentracing/opentracing-go"
jaeger "github.com/uber/jaeger-client-go"
"golang.org/x/net/context"
)

// Tracer is a middleware which traces incoming requests.
Expand All @@ -25,3 +28,16 @@ func (t Tracer) Wrap(next http.Handler) http.Handler {
maybeTracer.ServeHTTP(w, r)
})
}

func ExtractTraceID(ctx context.Context) (string, bool) {
sp := ot.SpanFromContext(ctx)
if sp == nil {
return "", false
}
sctx, ok := sp.Context().(jaeger.SpanContext)
if !ok {
return "", false
}

return sctx.TraceID().String(), true
}
5 changes: 5 additions & 0 deletions middleware/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ type Log struct {

// logWithRequest information from the request and context as fields.
func (l Log) logWithRequest(r *http.Request) logging.Interface {
traceID, ok := ExtractTraceID(r.Context())
if ok {
l.Log = l.Log.WithField("traceID", traceID)
}

return user.LogWith(r.Context(), l.Log)
}

Expand Down
3 changes: 2 additions & 1 deletion server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,15 +139,16 @@ func New(cfg Config) (*Server, error) {
RegisterInstrumentation(router)
}
httpMiddleware := []middleware.Interface{
middleware.Tracer{},
middleware.Log{
Log: log,
},
middleware.Instrument{
Duration: requestDuration,
RouteMatcher: router,
},
middleware.Tracer{},
}

httpMiddleware = append(httpMiddleware, cfg.HTTPMiddleware...)
httpServer := &http.Server{
ReadTimeout: cfg.HTTPServerReadTimeout,
Expand Down

0 comments on commit d906d37

Please sign in to comment.