From ef5540278fc8fbc706c00f8e0b185552e45686a9 Mon Sep 17 00:00:00 2001 From: aimuz Date: Thu, 11 May 2023 22:43:54 +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 https://github.com/kubernetes/klog/issues/370 Signed-off-by: aimuz --- klog.go | 3 +++ klog_test.go | 4 ++-- 2 files changed, 5 insertions(+), 2 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..7b6ebdb6 100644 --- a/klog_test.go +++ b/klog_test.go @@ -1484,13 +1484,13 @@ func TestInfoWithLogr(t *testing.T) { msg: "foo", expected: testLogrEntry{ severity: severity.InfoLog, - msg: "foo\n", + msg: "foo", }, }, { msg: "", expected: testLogrEntry{ severity: severity.InfoLog, - msg: "\n", + msg: "", }, }}