1
0
mirror of https://github.com/gofiber/fiber.git synced 2025-02-23 11:43:41 +00:00

🔥 Add logger middleware time zone support

This commit is contained in:
kallydev 2020-07-21 13:06:21 +08:00
parent f5f2d99f1b
commit a097820313
No known key found for this signature in database
GPG Key ID: F0BB1C41D9D9F0F6
2 changed files with 18 additions and 3 deletions

View File

@ -60,6 +60,11 @@ type (
// Optional. Default: 15:04:05
TimeFormat string
// TimeZone can be specified, such as "UTC" and "America/New_York" and "Asia/Chongqing", etc
//
// Optional. Default: Local
TimeZone string
// Output is a writter where logs are written
//
// Default: os.Stderr
@ -133,6 +138,7 @@ var LoggerConfigDefault = LoggerConfig{
Next: nil,
Format: "#${pid} - ${time} ${status} - ${latency} ${method} ${path}\n",
TimeFormat: "2006/01/02 15:04:05",
TimeZone: "Local",
Output: os.Stderr,
}
@ -203,14 +209,17 @@ func logger(config LoggerConfig) fiber.Handler {
var tmpl loggerTemplate
tmpl.new(config.Format, "${", "}")
timestamp := time.Now().Format(config.TimeFormat)
var location, err = time.LoadLocation(config.TimeZone)
if err != nil {
log.Fatalf("Logger: failed to load time zone: %e\n", err)
}
timestamp := time.Now().In(location).Format(config.TimeFormat)
// Update date/time every second in a separate go routine
if strings.Contains(config.Format, "${time}") {
go func() {
for {
mutex.Lock()
timestamp = time.Now().Format(config.TimeFormat)
timestamp = time.Now().In(location).Format(config.TimeFormat)
mutex.Unlock()
time.Sleep(500 * time.Millisecond)
}

View File

@ -34,6 +34,7 @@ func main() {
app.Use(middleware.Logger(middleware.LoggerConfig{
Format: "${time} ${method} ${path}",
TimeFormat: "15:04:05",
TimeZone: "Asia/Chongqing",
Output: os.Stdout,
}))
@ -87,6 +88,11 @@ type LoggerConfig struct {
// Optional. Default: 15:04:05
TimeFormat string
// TimeZone can be specified, such as "UTC" and "America/New_York" and "Asia/Chongqing", etc
//
// Optional. Default: Local
TimeZone string
// Output is a writter where logs are written
//
// Default: os.Stderr