Skip to content

Commit

Permalink
feat: add logger.WithFields (#2546)
Browse files Browse the repository at this point in the history
  • Loading branch information
kevwan authored Oct 22, 2022
1 parent 9cadab2 commit 06e4914
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
2 changes: 2 additions & 0 deletions core/logx/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,6 @@ type Logger interface {
WithContext(ctx context.Context) Logger
// WithDuration returns a new logger with the given duration.
WithDuration(d time.Duration) Logger
// WithFields returns a new logger with the given fields.
WithFields(fields ...LogField) Logger
}
5 changes: 5 additions & 0 deletions core/logx/richlogger.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,11 @@ func (l *richLogger) WithDuration(duration time.Duration) Logger {
return l
}

func (l *richLogger) WithFields(fields ...LogField) Logger {
l.fields = append(l.fields, fields...)
return l
}

func (l *richLogger) buildFields(fields ...LogField) []LogField {
fields = append(l.fields, fields...)
fields = append(fields, Field(callerKey, getCaller(callerDepth+l.callerSkip)))
Expand Down
17 changes: 17 additions & 0 deletions core/logx/richlogger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,23 @@ func TestLogWithCallerSkip(t *testing.T) {
assert.True(t, w.Contains(fmt.Sprintf("%s:%d", file, line+1)))
}

func TestLoggerWithFields(t *testing.T) {
w := new(mockWriter)
old := writer.Swap(w)
writer.lock.RLock()
defer func() {
writer.lock.RUnlock()
writer.Store(old)
}()

l := WithContext(context.Background()).WithFields(Field("foo", "bar"))
l.Info(testlog)

var val mockValue
assert.Nil(t, json.Unmarshal([]byte(w.String()), &val))
assert.Equal(t, "bar", val.Foo)
}

func validate(t *testing.T, body string, expectedTrace, expectedSpan bool) {
var val mockValue
dec := json.NewDecoder(strings.NewReader(body))
Expand Down

0 comments on commit 06e4914

Please sign in to comment.