Skip to content

Commit

Permalink
Merge pull request #916 from sirupsen/fix_race_getcaller
Browse files Browse the repository at this point in the history
Fix race getcaller
  • Loading branch information
dgsb committed Mar 6, 2019
2 parents c9b4f5a + cf1b9fd commit d7b6bf5
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
15 changes: 9 additions & 6 deletions entry.go
Expand Up @@ -156,20 +156,23 @@ func getPackageName(f string) string {

// getCaller retrieves the name of the first non-logrus calling function
func getCaller() *runtime.Frame {
// Restrict the lookback frames to avoid runaway lookups
pcs := make([]uintptr, maximumCallerDepth)
depth := runtime.Callers(minimumCallerDepth, pcs)
frames := runtime.CallersFrames(pcs[:depth])

// cache this package's fully-qualified name
callerInitOnce.Do(func() {
logrusPackage = getPackageName(runtime.FuncForPC(pcs[0]).Name())
pcs := make([]uintptr, 2)
_ = runtime.Callers(0, pcs)
logrusPackage = getPackageName(runtime.FuncForPC(pcs[1]).Name())

// now that we have the cache, we can skip a minimum count of known-logrus functions
// XXX this is dubious, the number of frames may vary store an entry in a logger interface
// XXX this is dubious, the number of frames may vary
minimumCallerDepth = knownLogrusFrames
})

// Restrict the lookback frames to avoid runaway lookups
pcs := make([]uintptr, maximumCallerDepth)
depth := runtime.Callers(minimumCallerDepth, pcs)
frames := runtime.CallersFrames(pcs[:depth])

for f, again := frames.Next(); again; f, again = frames.Next() {
pkg := getPackageName(f.Function)

Expand Down
17 changes: 17 additions & 0 deletions logrus_test.go
Expand Up @@ -743,3 +743,20 @@ func TestReportCallerOnTextFormatter(t *testing.T) {
l.Formatter.(*TextFormatter).DisableColors = true
l.WithFields(Fields{"func": "func", "file": "file"}).Info("test")
}

func TestSetReportCallerRace(t *testing.T) {
l := New()
l.Out = ioutil.Discard
l.SetReportCaller(true)

var wg sync.WaitGroup
wg.Add(100)

for i := 0; i < 100; i++ {
go func() {
l.Error("Some Error")
wg.Done()
}()
}
wg.Wait()
}

0 comments on commit d7b6bf5

Please sign in to comment.