Skip to content

Commit

Permalink
fix: SetLogger via klog.SetLogger will output an unexpected newline
Browse files Browse the repository at this point in the history
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]>
  • Loading branch information
aimuz committed May 11, 2023
1 parent 6ded808 commit 37def3b
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 3 deletions.
3 changes: 3 additions & 0 deletions klog.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
6 changes: 3 additions & 3 deletions klog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1522,15 +1522,15 @@ func TestInfoSWithLogr(t *testing.T) {
keysValues: []interface{}{},
expected: testLogrEntry{
severity: severity.InfoLog,
msg: "foo",
msg: "foo\n",
keysAndValues: []interface{}{},
},
}, {
msg: "bar",
keysValues: []interface{}{"a", 1},
expected: testLogrEntry{
severity: severity.InfoLog,
msg: "bar",
msg: "bar\n",
keysAndValues: []interface{}{"a", 1},
},
}}
Expand Down Expand Up @@ -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,
})
}
Expand Down

0 comments on commit 37def3b

Please sign in to comment.