1
0
mirror of https://github.com/gofiber/fiber.git synced 2025-02-21 22:53:09 +00:00

Merge pull request #684 from kiyonlin/improve-logger

🚀 use atomic.Value instead of sync.Mutex
This commit is contained in:
fenny 2020-07-29 08:55:51 +02:00 committed by GitHub
commit e47341ac5d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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: