Browse Source

text_formatter: fix race

tags/v0.11.1
Simon Eskildsen 2 years ago
parent
commit
11fbf0fa42
3 changed files with 12 additions and 6 deletions
  1. 1
    0
      examples/basic/basic.go
  2. 3
    0
      formatter_bench_test.go
  3. 8
    6
      text_formatter.go

+ 1
- 0
examples/basic/basic.go View File

@@ -2,6 +2,7 @@ package main
2 2
 
3 3
 import (
4 4
 	"github.com/Sirupsen/logrus"
5
+	"os"
5 6
 )
6 7
 
7 8
 var log = logrus.New()

+ 3
- 0
formatter_bench_test.go View File

@@ -80,11 +80,14 @@ func BenchmarkLargeJSONFormatter(b *testing.B) {
80 80
 }
81 81
 
82 82
 func doBenchmark(b *testing.B, formatter Formatter, fields Fields) {
83
+	logger := New()
84
+
83 85
 	entry := &Entry{
84 86
 		Time:    time.Time{},
85 87
 		Level:   InfoLevel,
86 88
 		Message: "message",
87 89
 		Data:    fields,
90
+		Logger:  logger,
88 91
 	}
89 92
 	var d []byte
90 93
 	var err error

+ 8
- 6
text_formatter.go View File

@@ -5,6 +5,7 @@ import (
5 5
 	"fmt"
6 6
 	"sort"
7 7
 	"strings"
8
+	"sync"
8 9
 	"time"
9 10
 )
10 11
 
@@ -49,8 +50,8 @@ type TextFormatter struct {
49 50
 	DisableSorting bool
50 51
 
51 52
 	// Whether the logger's out is to a terminal
52
-	isTerminal         bool
53
-	terminalDetermined bool
53
+	isTerminal   bool
54
+	terminalOnce sync.Once
54 55
 }
55 56
 
56 57
 func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
@@ -71,10 +72,11 @@ func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
71 72
 
72 73
 	prefixFieldClashes(entry.Data)
73 74
 
74
-	if !f.terminalDetermined {
75
-		f.isTerminal = IsTerminal(entry.Logger.Out)
76
-		f.terminalDetermined = true
77
-	}
75
+	f.terminalOnce.Do(func() {
76
+		if entry.Logger != nil {
77
+			f.isTerminal = IsTerminal(entry.Logger.Out)
78
+		}
79
+	})
78 80
 
79 81
 	isColored := (f.ForceColors || f.isTerminal) && !f.DisableColors
80 82
 

Loading…
Cancel
Save