Bladeren bron

feat: add logger.WithFields (#2546)

Kevin Wan 2 jaren geleden
bovenliggende
commit
06e4914e41
3 gewijzigde bestanden met toevoegingen van 24 en 0 verwijderingen
  1. 2 0
      core/logx/logger.go
  2. 5 0
      core/logx/richlogger.go
  3. 17 0
      core/logx/richlogger_test.go

+ 2 - 0
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
 }

+ 5 - 0
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)))

+ 17 - 0
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))