Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Print traceID with request #123

Merged
merged 1 commit into from
Aug 31, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,8 @@ import (

"github.com/opentracing-contrib/go-stdlib/nethttp"
"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 +27,17 @@ func (t Tracer) Wrap(next http.Handler) http.Handler {
maybeTracer.ServeHTTP(w, r)
})
}

// ExtractTraceID extracts the trace id, if any from the context.
func ExtractTraceID(ctx context.Context) (string, bool) {
sp := opentracing.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