Skip to content

Commit

Permalink
Logging: strip new lines and other control characters (prysmaticlabs#…
Browse files Browse the repository at this point in the history
…11185)

* Logging: strip new lines and other control characters

* Use strings.Map and only sanitize the field value

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
  • Loading branch information
prestonvanloon and prylabs-bulldozer[bot] authored Aug 8, 2022
1 parent 760d2fc commit ed1116e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
20 changes: 17 additions & 3 deletions runtime/logging/logrus-prefixed-formatter/formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"strings"
"sync"
"time"
"unicode"

"github.com/mgutz/ansi"
"github.com/sirupsen/logrus"
Expand Down Expand Up @@ -294,16 +295,29 @@ func (f *TextFormatter) printColored(b *bytes.Buffer, entry *logrus.Entry, keys
for _, k := range keys {
if k != "prefix" {
v := entry.Data[k]
format := " %s=%+v"

format := "%+v"
if k == logrus.ErrorKey {
format = " %s=%v" // To avoid printing stack traces for errors
format = "%v" // To avoid printing stack traces for errors
}
_, err = fmt.Fprintf(b, format, levelColor(k), v)

// Sanitize field values to remove new lines and other control characters.
s := sanitize(fmt.Sprintf(format, v))
_, err = fmt.Fprintf(b, " %s=%s", levelColor(k), s)
}
}
return
}

func sanitize(s string) string {
return strings.Map(func(r rune) rune {
if unicode.IsControl(r) {
return -1
}
return r
}, s)
}

func (f *TextFormatter) needsQuoting(text string) bool {
if f.QuoteEmptyFields && len(text) == 0 {
return true
Expand Down
12 changes: 12 additions & 0 deletions runtime/logging/logrus-prefixed-formatter/formatter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,15 @@ func TestFormatter_SuppressErrorStackTraces(t *testing.T) {
log.WithError(errors.Wrap(errFn(), "outer")).Error("test")
require.Equal(t, true, regexp.MustCompile(`test error=outer: inner\n\s*$`).MatchString(output.GetValue()), fmt.Sprintf("wrong log output: %s", output.GetValue()))
}

func TestFormatter_EscapesControlCharacters(t *testing.T) {
formatter := new(TextFormatter)
formatter.ForceFormatting = true
log := logrus.New()
log.Formatter = formatter
output := new(LogOutput)
log.Out = output

log.WithField("test", "foo\nbar").Error("testing things")
require.Equal(t, "[0000] ERROR testing things test=foobar"+"\n", output.GetValue())
}

0 comments on commit ed1116e

Please sign in to comment.