diff --git a/core/logx/logger.go b/core/logx/logger.go index ddb4ada7..a9ea0253 100644 --- a/core/logx/logger.go +++ b/core/logx/logger.go @@ -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 } diff --git a/core/logx/richlogger.go b/core/logx/richlogger.go index f73fddf9..e88c2f75 100644 --- a/core/logx/richlogger.go +++ b/core/logx/richlogger.go @@ -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))) diff --git a/core/logx/richlogger_test.go b/core/logx/richlogger_test.go index 7cf373a5..b629c537 100644 --- a/core/logx/richlogger_test.go +++ b/core/logx/richlogger_test.go @@ -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))