From 967f9430f61d6073b6ca3ab357c07948c779ad32 Mon Sep 17 00:00:00 2001 From: Nicholas Jackson Date: Fri, 9 Feb 2024 11:19:16 -0800 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Refactor:=20Remove=20mutex?= =?UTF-8?q?=20lock=20in=20logger=20middleware?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit While not all implementations of io.Write will be goroutine safe, the vast majority of users of the logger middleware are likely to use os.File, which does implement safe concurrent writes. If users require locking, they can implement this on an as-needed basis. The risk of having global locking is that a slow write can hold up the entire server. --- docs/api/middleware/logger.md | 4 ++++ middleware/logger/default_logger.go | 5 ----- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/docs/api/middleware/logger.md b/docs/api/middleware/logger.md index 8ec69d324c..9208eb4677 100644 --- a/docs/api/middleware/logger.md +++ b/docs/api/middleware/logger.md @@ -88,6 +88,10 @@ app.Use(logger.New(logger.Config{ })) ``` +:::tip +Writing to os.File is goroutine-safe, but if you are using a custom Output that is not goroutine-safe, make sure to implement locking to properly serialize writes. +::: + ## Config ### Config diff --git a/middleware/logger/default_logger.go b/middleware/logger/default_logger.go index 49a9202d93..cf925073a9 100644 --- a/middleware/logger/default_logger.go +++ b/middleware/logger/default_logger.go @@ -5,7 +5,6 @@ import ( "io" "os" "strconv" - "sync" "github.com/gofiber/fiber/v3" "github.com/gofiber/utils/v2" @@ -15,8 +14,6 @@ import ( "github.com/valyala/fasthttp" ) -var mu sync.Mutex - // default logger for fiber func defaultLoggerInstance(c fiber.Ctx, data *Data, cfg Config) error { // Alias colors @@ -128,9 +125,7 @@ func defaultLoggerInstance(c fiber.Ctx, data *Data, cfg Config) error { _, _ = buf.WriteString(err.Error()) //nolint:errcheck // This will never fail } - mu.Lock() writeLog(cfg.Output, buf.Bytes()) - mu.Unlock() if cfg.Done != nil { cfg.Done(c, buf.Bytes())