From 3327e8f3713071c5b2ee9a6e1c845279a4ec49ea Mon Sep 17 00:00:00 2001 From: Xiaochao Dong Date: Thu, 4 May 2023 15:27:51 +0800 Subject: [PATCH] Avoid expensive log.Valuer evaluation for disallowed levels (#6322) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Xiaochao Dong (@damnever) Signed-off-by: Giedrius Statkevičius --- pkg/logging/logger.go | 5 ++++- pkg/logging/logger_test.go | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 pkg/logging/logger_test.go diff --git a/pkg/logging/logger.go b/pkg/logging/logger.go index b711607b47..cca8853da5 100644 --- a/pkg/logging/logger.go +++ b/pkg/logging/logger.go @@ -46,11 +46,14 @@ func NewLogger(logLevel, logFormat, debugName string) log.Logger { logger = log.NewJSONLogger(log.NewSyncWriter(os.Stderr)) } + // Sort the logger chain to avoid expensive log.Valuer evaluation for disallowed level. + // Ref: https://github.com/go-kit/log/issues/14#issuecomment-945038252 + logger = log.With(logger, "ts", log.DefaultTimestampUTC, "caller", log.Caller(5)) logger = level.NewFilter(logger, lvl) if debugName != "" { logger = log.With(logger, "name", debugName) } - return log.With(logger, "ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller) + return logger } diff --git a/pkg/logging/logger_test.go b/pkg/logging/logger_test.go new file mode 100644 index 0000000000..2e4eb3f73f --- /dev/null +++ b/pkg/logging/logger_test.go @@ -0,0 +1,19 @@ +// Copyright (c) The Thanos Authors. +// Licensed under the Apache License 2.0. + +package logging + +import ( + "testing" + + "github.com/go-kit/log/level" +) + +func BenchmarkDisallowedLogLevels(b *testing.B) { + logger := NewLogger("warn", "logfmt", "benchmark") + + for i := 0; i < b.N; i++ { + level.Info(logger).Log("hello", "world", "number", i) + level.Debug(logger).Log("hello", "world", "number", i) + } +}