From 975c406ddb02ea083d859e81a86dcd8a3854217a Mon Sep 17 00:00:00 2001 From: David Bariod Date: Sat, 27 Oct 2018 15:21:30 +0200 Subject: [PATCH] Use a sync.Once to init the reportCaller data --- entry.go | 30 +++++++++++++++++++----------- logrus_test.go | 4 ++-- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/entry.go b/entry.go index df37550..5f40c58 100644 --- a/entry.go +++ b/entry.go @@ -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{ @@ -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 } } diff --git a/logrus_test.go b/logrus_test.go index d829369..2fe3653 100644 --- a/logrus_test.go +++ b/logrus_test.go @@ -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", @@ -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 }