From 929e7a94bda62f0f8166548930a95ced9981300e Mon Sep 17 00:00:00 2001 From: Julian Lawrence Date: Tue, 18 Jan 2022 23:27:29 -0800 Subject: [PATCH] fixed empty info log panic --- klog.go | 2 +- klog_test.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/klog.go b/klog.go index dacdf9112..73a0c930f 100644 --- a/klog.go +++ b/klog.go @@ -729,7 +729,7 @@ func (l *loggingT) printDepth(s severity, logger *logr.Logger, filter LogFilter, args = filter.Filter(args) } fmt.Fprint(buf, args...) - if buf.Bytes()[buf.Len()-1] != '\n' { + if buf.Len() == 0 || buf.Bytes()[buf.Len()-1] != '\n' { buf.WriteByte('\n') } l.output(s, logger, buf, depth, file, line, false) diff --git a/klog_test.go b/klog_test.go index a371845d9..17caaf4e0 100644 --- a/klog_test.go +++ b/klog_test.go @@ -1416,6 +1416,42 @@ func TestLogFilter(t *testing.T) { } } +func TestInfoWithLogr(t *testing.T) { + logger := new(testLogr) + + testDataInfo := []struct { + msg string + expected testLogrEntry + }{{ + msg: "foo", + expected: testLogrEntry{ + severity: infoLog, + msg: "foo\n", + }, + }, { + msg: "", + expected: testLogrEntry{ + severity: infoLog, + msg: "\n", + }, + }} + + for _, data := range testDataInfo { + t.Run(data.msg, func(t *testing.T) { + l := logr.New(logger) + SetLogger(l) + defer ClearLogger() + defer logger.reset() + + Info(data.msg) + + if !reflect.DeepEqual(logger.entries, []testLogrEntry{data.expected}) { + t.Errorf("expected: %+v; but got: %+v", []testLogrEntry{data.expected}, logger.entries) + } + }) + } +} + func TestInfoSWithLogr(t *testing.T) { logger := new(testLogr)