Skip to content

Commit

Permalink
Make clear AddFieldsToLogger only works for RDK loggers (#378)
Browse files Browse the repository at this point in the history
  • Loading branch information
cheukt authored Oct 28, 2024
1 parent 5600d4a commit f3560e9
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 9 deletions.
14 changes: 6 additions & 8 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,11 @@ func Sublogger(inp ZapCompatibleLogger, subname string) (loggerRet ZapCompatible
return loggerRet
}

// AddFieldsToLogger adds fields for logging to a given ZapCompatibleLogger instance.
// AddFieldsToLogger attempts to add fields for logging to a given ZapCompatibleLogger instance.
// This function uses reflection to dynamically add fields to the provided logger by
// calling its `WithFields` method if it is an RDK logger, or its `With` method if it is a Zap logger.
// If neither method is available, it logs a debug message and returns the original logger.
// calling its `WithFields` method if it is an RDK logger. If the logger is not an RDK logger,
// it logs a debug message and returns the original logger.
// Args is expected to be a list of key-value pair(s).
func AddFieldsToLogger(inp ZapCompatibleLogger, args ...interface{}) (loggerRet ZapCompatibleLogger) {
loggerRet = inp //nolint:wastedassign

Expand All @@ -101,11 +102,8 @@ func AddFieldsToLogger(inp ZapCompatibleLogger, args ...interface{}) (loggerRet
typ := reflect.TypeOf(inp)
with, ok := typ.MethodByName("WithFields")
if !ok {
with, ok = typ.MethodByName("With")
if !ok {
inp.Debugf("could not add fields to logger of type %s, returning self", typ.String())
return inp
}
inp.Debugf("could not add fields to logger of type %s, returning self", typ.String())
return inp
}

// When using reflection to call receiver methods, the first argument must be the object.
Expand Down
2 changes: 1 addition & 1 deletion logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ func TestLogWithZapLogger(t *testing.T) {
logger := golog.NewTestLogger(t)
loggerWith := AddFieldsToLogger(logger, "key", "value")
test.That(t, loggerWith, test.ShouldNotBeNil)
test.That(t, loggerWith, test.ShouldNotEqual, logger)
test.That(t, loggerWith, test.ShouldEqual, logger)
test.That(t, reflect.TypeOf(loggerWith), test.ShouldEqual, reflect.TypeOf(logger))
}

Expand Down

0 comments on commit f3560e9

Please sign in to comment.