diff --git a/ctx/ctx.go b/ctx/ctx.go index ad45492..58bac4a 100644 --- a/ctx/ctx.go +++ b/ctx/ctx.go @@ -188,9 +188,15 @@ func Interface(k string, v interface{}) logger.Field { } } -// TraceID returns a open telemetry trace ID context field. -func TraceID(k string, span trace.Span) logger.Field { - if !span.IsRecording() { +// Span represents an open telemetry span. +type Span interface { + IsRecording() bool + SpanContext() trace.SpanContext +} + +// TraceID returns an open telemetry trace ID context field. +func TraceID(k string, span Span) logger.Field { + if !span.IsRecording() || !span.SpanContext().HasTraceID() { return func(*logger.Event) {} } return func(e *logger.Event) { diff --git a/go.mod b/go.mod index c79c126..e57ad61 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,5 @@ go 1.16 require ( github.com/go-stack/stack v1.8.1 github.com/stretchr/testify v1.8.4 - go.opentelemetry.io/otel v1.17.0 go.opentelemetry.io/otel/trace v1.17.0 ) diff --git a/logger_test.go b/logger_test.go index 28dadb2..8b749a0 100644 --- a/logger_test.go +++ b/logger_test.go @@ -13,8 +13,6 @@ import ( "github.com/hamba/logger/v2/ctx" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/trace" ) @@ -231,7 +229,7 @@ func TestLogger_Stack(t *testing.T) { log.Info("some message", ctx.Stack("stack")) - want := `lvl=info msg="some message" stack=[github.com/hamba/logger/logger/logger_test.go:232]` + "\n" + want := `lvl=info msg="some message" stack=[github.com/hamba/logger/logger/logger_test.go:230]` + "\n" assert.Equal(t, want, buf.String()) } @@ -265,19 +263,14 @@ type fakeSpan struct { ID byte } -func (s *fakeSpan) End(...trace.SpanEndOption) {} -func (s *fakeSpan) AddEvent(string, ...trace.EventOption) {} -func (s *fakeSpan) IsRecording() bool { return s.Recording } -func (s *fakeSpan) RecordError(error, ...trace.EventOption) {} -func (s *fakeSpan) SetStatus(codes.Code, string) {} -func (s *fakeSpan) SetName(string) {} -func (s *fakeSpan) SetAttributes(...attribute.KeyValue) {} -func (s *fakeSpan) TracerProvider() trace.TracerProvider { return nil } +func (s *fakeSpan) IsRecording() bool { + return s.Recording +} func (s *fakeSpan) SpanContext() trace.SpanContext { return trace.NewSpanContext(trace.SpanContextConfig{ - TraceID: trace.TraceID([16]byte{1}), - SpanID: trace.SpanID([8]byte{s.ID}), + TraceID: [16]byte{1}, + SpanID: [8]byte{s.ID}, Remote: false, }) }