Skip to content

Commit 8aba960

Browse files
committed
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 <[email protected]>
1 parent 6ded808 commit 8aba960

File tree

2 files changed

+6
-3
lines changed

2 files changed

+6
-3
lines changed

klog.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -873,6 +873,9 @@ func (l *loggingT) output(s severity.Severity, logger *logWriter, buf *buffer.Bu
873873
if logger.writeKlogBuffer != nil {
874874
logger.writeKlogBuffer(data)
875875
} else {
876+
if data[len(data)-1] == '\n' {
877+
data = data[:len(data)-1]
878+
}
876879
// TODO: set 'severity' and caller information as structured log info
877880
// keysAndValues := []interface{}{"severity", severityName[s], "file", file, "line", line}
878881
if s == severity.ErrorLog {

klog_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1522,15 +1522,15 @@ func TestInfoSWithLogr(t *testing.T) {
15221522
keysValues: []interface{}{},
15231523
expected: testLogrEntry{
15241524
severity: severity.InfoLog,
1525-
msg: "foo",
1525+
msg: "foo\n",
15261526
keysAndValues: []interface{}{},
15271527
},
15281528
}, {
15291529
msg: "bar",
15301530
keysValues: []interface{}{"a", 1},
15311531
expected: testLogrEntry{
15321532
severity: severity.InfoLog,
1533-
msg: "bar",
1533+
msg: "bar\n",
15341534
keysAndValues: []interface{}{"a", 1},
15351535
},
15361536
}}
@@ -1810,7 +1810,7 @@ func (l *testLogr) Info(level int, msg string, keysAndValues ...interface{}) {
18101810
defer l.mutex.Unlock()
18111811
l.entries = append(l.entries, testLogrEntry{
18121812
severity: severity.InfoLog,
1813-
msg: msg,
1813+
msg: msg + "\n",
18141814
keysAndValues: keysAndValues,
18151815
})
18161816
}

0 commit comments

Comments
 (0)