From 11fbf0fa42b837cdd5b234470b53d03bad9e5041 Mon Sep 17 00:00:00 2001 From: Simon Eskildsen Date: Sun, 5 Feb 2017 19:10:19 -0500 Subject: [PATCH] text_formatter: fix race --- examples/basic/basic.go | 1 + formatter_bench_test.go | 3 +++ text_formatter.go | 14 ++++++++------ 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/examples/basic/basic.go b/examples/basic/basic.go index a1623ec..ea7e551 100644 --- a/examples/basic/basic.go +++ b/examples/basic/basic.go @@ -2,6 +2,7 @@ package main import ( "github.com/Sirupsen/logrus" + "os" ) var log = logrus.New() diff --git a/formatter_bench_test.go b/formatter_bench_test.go index c6d290c..d948158 100644 --- a/formatter_bench_test.go +++ b/formatter_bench_test.go @@ -80,11 +80,14 @@ func BenchmarkLargeJSONFormatter(b *testing.B) { } func doBenchmark(b *testing.B, formatter Formatter, fields Fields) { + logger := New() + entry := &Entry{ Time: time.Time{}, Level: InfoLevel, Message: "message", Data: fields, + Logger: logger, } var d []byte var err error diff --git a/text_formatter.go b/text_formatter.go index f75e13e..b4dffa1 100644 --- a/text_formatter.go +++ b/text_formatter.go @@ -5,6 +5,7 @@ import ( "fmt" "sort" "strings" + "sync" "time" ) @@ -49,8 +50,8 @@ type TextFormatter struct { DisableSorting bool // Whether the logger's out is to a terminal - isTerminal bool - terminalDetermined bool + isTerminal bool + terminalOnce sync.Once } func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { @@ -71,10 +72,11 @@ func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { prefixFieldClashes(entry.Data) - if !f.terminalDetermined { - f.isTerminal = IsTerminal(entry.Logger.Out) - f.terminalDetermined = true - } + f.terminalOnce.Do(func() { + if entry.Logger != nil { + f.isTerminal = IsTerminal(entry.Logger.Out) + } + }) isColored := (f.ForceColors || f.isTerminal) && !f.DisableColors