From 8aba9601fa023d4cc537639a38bac2d85dc9dcfb Mon Sep 17 00:00:00 2001 From: aimuz Date: Thu, 11 May 2023 22:36:12 +0800 Subject: [PATCH] fix: SetLogger via klog.SetLogger will output an unexpected newline klog always adds a newline to the msg. klog will work fine without klog. Set logr with klog.SetLogger, and klog will also pass the msg with the newline added to logr, which will result in an accidental newline being added. step1: klog.Info("hello world") step2: msg = msg + "\n" step3: stdout.W(msg) or logr.Info(msg[:len(msg)-1]) fix #370 Signed-off-by: aimuz --- klog.go | 3 +++ klog_test.go | 6 +++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/klog.go b/klog.go index 152f8a6b..3462978b 100644 --- a/klog.go +++ b/klog.go @@ -873,6 +873,9 @@ func (l *loggingT) output(s severity.Severity, logger *logWriter, buf *buffer.Bu if logger.writeKlogBuffer != nil { logger.writeKlogBuffer(data) } else { + if data[len(data)-1] == '\n' { + data = data[:len(data)-1] + } // TODO: set 'severity' and caller information as structured log info // keysAndValues := []interface{}{"severity", severityName[s], "file", file, "line", line} if s == severity.ErrorLog { diff --git a/klog_test.go b/klog_test.go index 76303e06..c31b7fb1 100644 --- a/klog_test.go +++ b/klog_test.go @@ -1522,7 +1522,7 @@ func TestInfoSWithLogr(t *testing.T) { keysValues: []interface{}{}, expected: testLogrEntry{ severity: severity.InfoLog, - msg: "foo", + msg: "foo\n", keysAndValues: []interface{}{}, }, }, { @@ -1530,7 +1530,7 @@ func TestInfoSWithLogr(t *testing.T) { keysValues: []interface{}{"a", 1}, expected: testLogrEntry{ severity: severity.InfoLog, - msg: "bar", + msg: "bar\n", keysAndValues: []interface{}{"a", 1}, }, }} @@ -1810,7 +1810,7 @@ func (l *testLogr) Info(level int, msg string, keysAndValues ...interface{}) { defer l.mutex.Unlock() l.entries = append(l.entries, testLogrEntry{ severity: severity.InfoLog, - msg: msg, + msg: msg + "\n", keysAndValues: keysAndValues, }) }