From 10d6b28edf1236dd56e9d2c3f0d7a81787456d02 Mon Sep 17 00:00:00 2001 From: Mike Pye Date: Fri, 5 Jun 2020 03:25:06 +0100 Subject: [PATCH] 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 --- logger/logrus.go | 4 ++-- test/logger_test.go | 12 +++++++++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/logger/logrus.go b/logger/logrus.go index 464f691..e4f7a67 100644 --- a/logger/logrus.go +++ b/logger/logrus.go @@ -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, } diff --git a/test/logger_test.go b/test/logger_test.go index 502b509..2d63124 100644 --- a/test/logger_test.go +++ b/test/logger_test.go @@ -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") +}