Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix race getcaller #916

Merged
merged 2 commits into from Mar 6, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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()
}