From 76c67ca05a3871ebd0efe56f13cd6db201ed02e3 Mon Sep 17 00:00:00 2001 From: kiyon Date: Wed, 29 Jul 2020 14:42:17 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=80=20use=20atomic.Value=20instead=20o?= =?UTF-8?q?f=20sync.Mutex?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit To improve the performance and precision --- middleware/logger.go | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/middleware/logger.go b/middleware/logger.go index 89d84fa2..1d8fbc4f 100644 --- a/middleware/logger.go +++ b/middleware/logger.go @@ -7,7 +7,7 @@ import ( "os" "strconv" "strings" - "sync" + "sync/atomic" "time" fiber "github.com/gofiber/fiber" @@ -207,20 +207,18 @@ func logger(config LoggerConfig) fiber.Handler { } } - // Middleware settings - var mutex sync.RWMutex var tmpl loggerTemplate tmpl.new(config.Format, "${", "}") - timestamp := nowTimeString(config.timeZoneLocation, config.TimeFormat) - // Update date/time every second in a separate go routine + + var timestamp atomic.Value + timestamp.Store(nowTimeString(config.timeZoneLocation, config.TimeFormat)) + // Update date/time every millisecond in a separate go routine if strings.Contains(config.Format, "${time}") { go func() { for { - mutex.Lock() - timestamp = nowTimeString(config.timeZoneLocation, config.TimeFormat) - mutex.Unlock() - time.Sleep(500 * time.Millisecond) + time.Sleep(time.Millisecond) + timestamp.Store(nowTimeString(config.timeZoneLocation, config.TimeFormat)) } }() } @@ -243,9 +241,7 @@ func logger(config LoggerConfig) fiber.Handler { _, err := tmpl.executeFunc(buf, func(w io.Writer, tag string) (int, error) { switch tag { case LoggerTagTime: - mutex.RLock() - defer mutex.RUnlock() - return buf.WriteString(timestamp) + return buf.WriteString(timestamp.Load().(string)) case LoggerTagReferer: return buf.WriteString(c.Get(fiber.HeaderReferer)) case LoggerTagProtocol: