From 6f8fe448c7a021bbdac78e5d848e2fb7346a1d99 Mon Sep 17 00:00:00 2001 From: Joe Elliott Date: Wed, 12 Aug 2020 00:07:48 -0400 Subject: [PATCH] Add span and trace id to hotrod logs (#2384) Signed-off-by: Joe Elliott --- examples/hotrod/pkg/log/factory.go | 13 +++++++++++-- examples/hotrod/pkg/log/spanlogger.go | 13 +++++++------ 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/examples/hotrod/pkg/log/factory.go b/examples/hotrod/pkg/log/factory.go index e64e1ae48b1..d32a98a97b4 100644 --- a/examples/hotrod/pkg/log/factory.go +++ b/examples/hotrod/pkg/log/factory.go @@ -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" ) @@ -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() } diff --git a/examples/hotrod/pkg/log/spanlogger.go b/examples/hotrod/pkg/log/spanlogger.go index c22234c078e..a5ab6f7de82 100644 --- a/examples/hotrod/pkg/log/spanlogger.go +++ b/examples/hotrod/pkg/log/spanlogger.go @@ -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) {