Skip to content

Commit

Permalink
Use a sync.Once to init the reportCaller data
Browse files Browse the repository at this point in the history
  • Loading branch information
dgsb committed Oct 27, 2018
1 parent 5fcd19e commit 975c406
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 13 deletions.
30 changes: 19 additions & 11 deletions entry.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,23 @@ import (
"time"
)

var bufferPool *sync.Pool
var (
bufferPool *sync.Pool

// qualified package name, cached at first use
var LogrusPackage string
// qualified package name, cached at first use
logrusPackage string

// Positions in the call stack when tracing to report the calling method
var minimumCallerDepth int
// Positions in the call stack when tracing to report the calling method
minimumCallerDepth int

const maximumCallerDepth int = 25
const knownLogrusFrames int = 4
// Used for caller information initialisation
callerInitOnce sync.Once
)

const (
maximumCallerDepth int = 25
knownLogrusFrames int = 4
)

func init() {
bufferPool = &sync.Pool{
Expand Down Expand Up @@ -143,19 +150,20 @@ func getCaller() (method string) {
depth := runtime.Callers(minimumCallerDepth, pcs)

// cache this package's fully-qualified name
if LogrusPackage == "" {
LogrusPackage = getPackageName(runtime.FuncForPC(pcs[0]).Name())
callerInitOnce.Do(func() {
logrusPackage = getPackageName(runtime.FuncForPC(pcs[0]).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
minimumCallerDepth = knownLogrusFrames
}
})

for i := 0; i < depth; i++ {
fullFuncName := runtime.FuncForPC(pcs[i]).Name()
pkg := getPackageName(fullFuncName)

// If the caller isn't part of this package, we're done
if pkg != LogrusPackage {
if pkg != logrusPackage {
return fullFuncName
}
}
Expand Down
4 changes: 2 additions & 2 deletions logrus_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ func logSomething(t *testing.T, message string) Fields {
logger.ReportCaller = true

// override the filter to allow reporting of functions within the logrus package
LogrusPackage = "bogusForTesting"
logrusPackage = "bogusForTesting"

entry := logger.WithFields(Fields{
"foo": "bar",
Expand All @@ -104,7 +104,7 @@ func logSomething(t *testing.T, message string) Fields {
assert.Nil(t, err)

// now clear the override so as not to mess with other usage
LogrusPackage = ""
logrusPackage = ""
return fields
}

Expand Down

0 comments on commit 975c406

Please sign in to comment.