Skip to content

Commit

Permalink
Add span and trace id to hotrod logs (#2384)
Browse files Browse the repository at this point in the history
Signed-off-by: Joe Elliott <number101010@gmail.com>
  • Loading branch information
joe-elliott authored Aug 12, 2020
1 parent 6e04d9d commit 6f8fe44
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
13 changes: 11 additions & 2 deletions examples/hotrod/pkg/log/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"context"

"github.com/opentracing/opentracing-go"
"github.com/uber/jaeger-client-go"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
Expand All @@ -44,8 +45,16 @@ func (b Factory) Bg() Logger {
// echo-ed into the span.
func (b Factory) For(ctx context.Context) Logger {
if span := opentracing.SpanFromContext(ctx); span != nil {
// TODO for Jaeger span extract trace/span IDs as fields
return spanLogger{span: span, logger: b.logger}
logger := spanLogger{span: span, logger: b.logger}

if jaegerCtx, ok := span.Context().(jaeger.SpanContext); ok {
logger.spanFields = []zapcore.Field{
zap.String("trace_id", jaegerCtx.TraceID().String()),
zap.String("span_id", jaegerCtx.SpanID().String()),
}
}

return logger
}
return b.Bg()
}
Expand Down
13 changes: 7 additions & 6 deletions examples/hotrod/pkg/log/spanlogger.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,29 +26,30 @@ import (
)

type spanLogger struct {
logger *zap.Logger
span opentracing.Span
logger *zap.Logger
span opentracing.Span
spanFields []zapcore.Field
}

func (sl spanLogger) Info(msg string, fields ...zapcore.Field) {
sl.logToSpan("info", msg, fields...)
sl.logger.Info(msg, fields...)
sl.logger.Info(msg, append(sl.spanFields, fields...)...)
}

func (sl spanLogger) Error(msg string, fields ...zapcore.Field) {
sl.logToSpan("error", msg, fields...)
sl.logger.Error(msg, fields...)
sl.logger.Error(msg, append(sl.spanFields, fields...)...)
}

func (sl spanLogger) Fatal(msg string, fields ...zapcore.Field) {
sl.logToSpan("fatal", msg, fields...)
tag.Error.Set(sl.span, true)
sl.logger.Fatal(msg, fields...)
sl.logger.Fatal(msg, append(sl.spanFields, fields...)...)
}

// With creates a child logger, and optionally adds some context fields to that logger.
func (sl spanLogger) With(fields ...zapcore.Field) Logger {
return spanLogger{logger: sl.logger.With(fields...), span: sl.span}
return spanLogger{logger: sl.logger.With(fields...), span: sl.span, spanFields: sl.spanFields}
}

func (sl spanLogger) logToSpan(level string, msg string, fields ...zapcore.Field) {
Expand Down

0 comments on commit 6f8fe44

Please sign in to comment.