From 06d91bdd9f96669d3663ee189d427f30c245bc99 Mon Sep 17 00:00:00 2001 From: Martin Holst Swende Date: Wed, 6 Sep 2023 14:48:09 +0200 Subject: [PATCH] log: avoid stack lookups when not needed/used --- log/logger.go | 9 ++++++--- log/logger_test.go | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) create mode 100644 log/logger_test.go diff --git a/log/logger.go b/log/logger.go index 4e471a22da..c12c067095 100644 --- a/log/logger.go +++ b/log/logger.go @@ -177,19 +177,22 @@ type logger struct { } func (l *logger) write(msg string, lvl Lvl, ctx []interface{}, skip int) { - l.h.Log(&Record{ + record := &Record{ Time: time.Now(), Lvl: lvl, Msg: msg, Ctx: newContext(l.ctx, ctx), - Call: stack.Caller(skip), KeyNames: RecordKeyNames{ Time: timeKey, Msg: msgKey, Lvl: lvlKey, Ctx: ctxKey, }, - }) + } + if locationEnabled.Load() { + record.Call = stack.Caller(skip) + } + l.h.Log(record) } func (l *logger) New(ctx ...interface{}) Logger { diff --git a/log/logger_test.go b/log/logger_test.go new file mode 100644 index 0000000000..b35e5493c7 --- /dev/null +++ b/log/logger_test.go @@ -0,0 +1,14 @@ +package log + +import ( + "os" + "testing" +) + +func BenchmarkTraceLogging(b *testing.B) { + Root().SetHandler(LvlFilterHandler(LvlInfo, StreamHandler(os.Stderr, TerminalFormat(true)))) + b.ResetTimer() + for i := 0; i < b.N; i++ { + Trace("a message", "v", i) + } +}