From 9f3fd50a0eadf8ee1cecbe31e6d6b232ac40a283 Mon Sep 17 00:00:00 2001 From: Simon Sawert Date: Sun, 1 May 2022 22:09:44 +0200 Subject: [PATCH] Map V-level logging to logrus named logging After looking at the code for other logr implementations such as zapr and zerologr it makes more sens that logrus also should try to map logr V-level logging to named logging as close as possible. * V0 is kept as severity Info * V1 is logged as severity Debug * V2 is logged as severity Trace --- logrusr.go | 12 +++++++++--- logrusr_test.go | 19 ++++++++++++++++++- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/logrusr.go b/logrusr.go index 4edd9a1..2dda1c3 100644 --- a/logrusr.go +++ b/logrusr.go @@ -109,9 +109,15 @@ func (l *logrusr) Info(level int, msg string, keysAndValues ...interface{}) { l.logger = l.logger.WithField("caller", c) } - l.logger. - WithFields(listToLogrusFields(l.defaultFormatter, keysAndValues...)). - Info(msg) + log := l.logger.WithFields(listToLogrusFields(l.defaultFormatter, keysAndValues...)) + + if level <= 0 { + log.Info(msg) + } else if level == 1 { + log.Debug(msg) + } else { + log.Trace(msg) + } } // Error logs error messages. Since the log will be written with `Error` level diff --git a/logrusr_test.go b/logrusr_test.go index eb602ce..6fa74be 100644 --- a/logrusr_test.go +++ b/logrusr_test.go @@ -87,10 +87,27 @@ func TestLogging(t *testing.T) { return logrus.New() }, logFunc: func(log logr.Logger) { + log.V(1).Info("hello, world") log.V(2).Info("hello, world") }, assertions: nil, }, + { + description: "V(1) logging with debug level set is shown", + logrusLogger: func() logrus.FieldLogger { + l := logrus.New() + l.SetLevel(logrus.TraceLevel) + + return l + }, + logFunc: func(log logr.Logger) { + log.V(1).Info("hello, world") + }, + assertions: map[string]string{ + "level": "debug", + "msg": "hello, world", + }, + }, { description: "V(2) logging with trace level set is shown", logrusLogger: func() logrus.FieldLogger { @@ -103,7 +120,7 @@ func TestLogging(t *testing.T) { log.V(2).Info("hello, world") }, assertions: map[string]string{ - "level": "info", + "level": "trace", "msg": "hello, world", }, },