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 ef55402
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 2 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
4 changes: 2 additions & 2 deletions klog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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: "",
},
}}

Expand Down

0 comments on commit ef55402

Please sign in to comment.