Skip to content

Commit 06e4914

Browse files
authored
feat: add logger.WithFields (#2546)
1 parent 9cadab2 commit 06e4914

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

core/logx/logger.go

+2
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,6 @@ type Logger interface {
4545
WithContext(ctx context.Context) Logger
4646
// WithDuration returns a new logger with the given duration.
4747
WithDuration(d time.Duration) Logger
48+
// WithFields returns a new logger with the given fields.
49+
WithFields(fields ...LogField) Logger
4850
}

core/logx/richlogger.go

+5
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,11 @@ func (l *richLogger) WithDuration(duration time.Duration) Logger {
123123
return l
124124
}
125125

126+
func (l *richLogger) WithFields(fields ...LogField) Logger {
127+
l.fields = append(l.fields, fields...)
128+
return l
129+
}
130+
126131
func (l *richLogger) buildFields(fields ...LogField) []LogField {
127132
fields = append(l.fields, fields...)
128133
fields = append(fields, Field(callerKey, getCaller(callerDepth+l.callerSkip)))

core/logx/richlogger_test.go

+17
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,23 @@ func TestLogWithCallerSkip(t *testing.T) {
272272
assert.True(t, w.Contains(fmt.Sprintf("%s:%d", file, line+1)))
273273
}
274274

275+
func TestLoggerWithFields(t *testing.T) {
276+
w := new(mockWriter)
277+
old := writer.Swap(w)
278+
writer.lock.RLock()
279+
defer func() {
280+
writer.lock.RUnlock()
281+
writer.Store(old)
282+
}()
283+
284+
l := WithContext(context.Background()).WithFields(Field("foo", "bar"))
285+
l.Info(testlog)
286+
287+
var val mockValue
288+
assert.Nil(t, json.Unmarshal([]byte(w.String()), &val))
289+
assert.Equal(t, "bar", val.Foo)
290+
}
291+
275292
func validate(t *testing.T, body string, expectedTrace, expectedSpan bool) {
276293
var val mockValue
277294
dec := json.NewDecoder(strings.NewReader(body))

0 commit comments

Comments
 (0)