From b7b9acad87e1873da8b56d1cbdf494c1f53da7bc Mon Sep 17 00:00:00 2001 From: Cedric Bail Date: Fri, 26 May 2023 14:50:33 -0600 Subject: [PATCH] Remove call to isatty from the hot path. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The result from isatty is immutable during the run of the program and is triggering a heavy system call that significantly slow down answering request. $ benchstat before.txt after.txt goos: darwin goarch: amd64 pkg: github.com/gin-contrib/logger cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz │ before.txt │ after.txt │ │ sec/op │ sec/op vs base │ Logger 2.924µ ± 2% 1.617µ ± 12% -44.70% (p=0.000 n=10) Logger-2 1649.0n ± 2% 766.1n ± 1% -53.54% (p=0.000 n=10) Logger-4 1009.5n ± 11% 496.6n ± 12% -50.80% (p=0.000 n=10) Logger-8 853.4n ± 3% 396.4n ± 12% -53.56% (p=0.000 n=10) geomean 1.428µ 702.7n -50.78% --- logger.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/logger.go b/logger.go index d678d73..c894c60 100644 --- a/logger.go +++ b/logger.go @@ -32,6 +32,8 @@ type config struct { serverErrorLevel zerolog.Level } +var isTerm bool = isatty.IsTerminal(os.Stdout.Fd()) + // SetLogger initializes the logging middleware. func SetLogger(opts ...Option) gin.HandlerFunc { cfg := &config{ @@ -56,7 +58,6 @@ func SetLogger(opts ...Option) gin.HandlerFunc { } return func(c *gin.Context) { - isTerm := isatty.IsTerminal(os.Stdout.Fd()) l := zerolog.New(cfg.output). Output( zerolog.ConsoleWriter{