From 70067a17547c66c7e7674455b297fb0215cb731c Mon Sep 17 00:00:00 2001 From: nickajacks1 <128185314+nickajacks1@users.noreply.github.com> Date: Fri, 9 Feb 2024 16:32:37 -0800 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Refactor:=20Remove=20mutex?= =?UTF-8?q?=20lock=20in=20logger=20middleware=20(#2840)?= 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 8ec69d32..9208eb46 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 22da35bf..0070b720 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()) } - mu.Lock() writeLog(cfg.Output, buf.Bytes()) - mu.Unlock() if cfg.Done != nil { cfg.Done(c, buf.Bytes())