Skip to content

Commit

Permalink
fix(logging): inconsistency between go kit Logger and spanLogger
Browse files Browse the repository at this point in the history
Only log.Valuer passed via log.With are treated as dynamic argument in go kit log. The change makes spanLogger consistent with go kit.
  • Loading branch information
Reasno committed Oct 29, 2021
1 parent 2357197 commit 0d5fd83
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 19 deletions.
22 changes: 5 additions & 17 deletions logging/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,14 +106,14 @@ type spanLogger struct {
}

func (s spanLogger) Log(keyvals ...interface{}) error {
s.kvs = append(s.kvs, keyvals...)
for k := range s.kvs {
if f, ok := s.kvs[k].(log.Valuer); ok {
s.kvs[k] = f()
}
}
s.kvs = append(s.kvs, keyvals...)
s.span.LogKV(s.kvs...)
return s.base.Log(s.kvs...)
return s.base.Log(keyvals...)
}

// WithContext decorates the log.Logger with information form context. If there is an opentracing span
Expand All @@ -127,27 +127,15 @@ func WithContext(logger log.Logger, ctx context.Context) log.Logger {
args = append(args, kv.Key, kv.Val)
}

base := log.With(logger, args...)

span := opentracing.SpanFromContext(ctx)
if span == nil {
return withContext(logger, ctx)
return base
}
return spanLogger{span: span, base: logger, kvs: args}
}

func withContext(logger log.Logger, ctx context.Context) log.Logger {
var args []interface{}

bag := ctxmeta.GetBaggage(ctx)
for _, kv := range bag.Slice() {
args = append(args, kv.Key, kv.Val)
}

return log.With(
logger,
args...,
)
}

type levelLogger struct {
log.Logger
}
Expand Down
4 changes: 2 additions & 2 deletions logging/log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ func TestSpanLogger(t *testing.T) {
spanLogger{
span: &mock,
base: log.NewNopLogger(),
kvs: []interface{}{"foo", "bar"},
}.Log("baz", log.Valuer(func() interface{} { return "qux" }))
kvs: []interface{}{"foo", log.Valuer(func() interface{} { return "bar" })},
}.Log("baz", "qux")

assert.Equal(t, []interface{}{"foo", "bar", "baz", "qux"}, mock.received)
}

0 comments on commit 0d5fd83

Please sign in to comment.