mirror of
https://gitlab.com/pulsechaincom/prysm-pulse.git
synced 2024-12-22 03:30:35 +00:00
Logging: strip new lines and other control characters (#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>
This commit is contained in:
parent
760d2fcfbc
commit
ed1116e578
@ -10,6 +10,7 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/mgutz/ansi"
|
||||
"github.com/sirupsen/logrus"
|
||||
@ -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
|
||||
|
@ -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())
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user