Use FieldLogger interface to represent logrus logger (#75)

The FieldLogger interface is satisfied by either *Logger or *Entry.
Accepting this interface in place of the concrete *Logger type allows
users to inject a logger with some fields already set. For example, the
application developer might want all logging from the library to have a
`subsystem=kcl` field.

Signed-off-by: Mike Pye <mail@mdpye.co.uk>
This commit is contained in:
Mike Pye 2020-06-05 03:25:06 +01:00 committed by Tao Jiang
parent 384482169c
commit 10d6b28edf
2 changed files with 13 additions and 3 deletions

View file

@ -34,12 +34,12 @@ type LogrusLogEntry struct {
}
type LogrusLogger struct {
logger *logrus.Logger
logger logrus.FieldLogger
}
// NewLogrusLogger adapts existing logrus logger to Logger interface.
// The call is responsible for configuring logrus logger appropriately.
func NewLogrusLogger(lLogger *logrus.Logger) Logger {
func NewLogrusLogger(lLogger logrus.FieldLogger) Logger {
return &LogrusLogger{
logger: lLogger,
}

View file

@ -79,10 +79,20 @@ func TestLogrusLoggerWithConfig(t *testing.T) {
}
func TestLogrusLogger(t *testing.T) {
// adapts to Logger interface
// adapts to Logger interface from *logrus.Logger
log := logger.NewLogrusLogger(logrus.StandardLogger())
contextLogger := log.WithFields(logger.Fields{"key1": "value1"})
contextLogger.Debugf("Starting with logrus")
contextLogger.Infof("Logrus is awesome")
}
func TestLogrusLoggerWithFieldsAtInit(t *testing.T) {
// adapts to Logger interface from *logrus.Entry
fieldLogger := logrus.StandardLogger().WithField("key0", "value0")
log := logger.NewLogrusLogger(fieldLogger)
contextLogger := log.WithFields(logger.Fields{"key1": "value1"})
contextLogger.Debugf("Starting with logrus")
contextLogger.Infof("Structured logging is awesome")
}