From 92aece568bf7ac7d2008928efa09da14b63395fe Mon Sep 17 00:00:00 2001 From: Dennis de Reus Date: Fri, 29 Dec 2017 20:26:35 +0100 Subject: [PATCH] TextFormatter behaviour aligned with stdlib log (fixes #167) stdlib `log` adds a newline at the end of a message if none is present, otherwise does not. Before this change logrus would always add a newline, resulting in inconsistent behaviour if stdlib log was replaced with logrus, and a user would e.g. use 'log.printf("test\n")' --- text_formatter.go | 4 ++++ text_formatter_test.go | 23 +++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/text_formatter.go b/text_formatter.go index 61b21ca..9f7dc35 100644 --- a/text_formatter.go +++ b/text_formatter.go @@ -126,6 +126,10 @@ func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []strin levelText := strings.ToUpper(entry.Level.String())[0:4] + // Remove a single newline if it already exists in the message to keep + // the behavior of logrus text_formatter the same as the stdlib log package + entry.Message = strings.TrimSuffix(entry.Message, "\n") + if f.DisableTimestamp { fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m %-44s ", levelColor, levelText, entry.Message) } else if !f.FullTimestamp { diff --git a/text_formatter_test.go b/text_formatter_test.go index d93b931..aea8727 100644 --- a/text_formatter_test.go +++ b/text_formatter_test.go @@ -137,5 +137,28 @@ func TestDisableTimestampWithColoredOutput(t *testing.T) { } } +func TestNewlineBehavior(t *testing.T) { + tf := &TextFormatter{ForceColors: true} + + // Ensure a single new line is removed as per stdlib log + e := NewEntry(StandardLogger()) + e.Message = "test message\n" + b, _ := tf.Format(e) + if bytes.Contains(b, []byte("test message\n")) { + t.Error("first newline at end of Entry.Message resulted in unexpected 2 newlines in output. Expected newline to be removed.") + } + + // Ensure a double new line is reduced to a single new line + e = NewEntry(StandardLogger()) + e.Message = "test message\n\n" + b, _ = tf.Format(e) + if bytes.Contains(b, []byte("test message\n\n")) { + t.Error("Double newline at end of Entry.Message resulted in unexpected 2 newlines in output. Expected single newline") + } + if !bytes.Contains(b, []byte("test message\n")) { + t.Error("Double newline at end of Entry.Message did not result in a single newline after formatting") + } +} + // TODO add tests for sorting etc., this requires a parser for the text // formatter output.