Skip to content

Commit

Permalink
optimize: solve concurrency problems with atomic.Value (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
L2ncE authored Nov 4, 2022
1 parent 6627fc3 commit 4157873
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions accesslog/accesslog.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import (
"os"
"strconv"
"strings"
"sync/atomic"
"time"

"github.com/cloudwego/hertz/pkg/app"
Expand All @@ -65,14 +66,14 @@ func New(opts ...Option) app.HandlerFunc {
tmpl := fasttemplate.New(cfg.format, "${", "}")

// Create correct time format
var timestamp string
var timestamp atomic.Value

// Update date/time every 500 milliseconds in a separate go routine
if strings.Contains(cfg.format, "${time}") {
go func() {
for {
time.Sleep(cfg.timeInterval)
timestamp = time.Now().In(cfg.timeZoneLocation).Format(cfg.timeFormat)
timestamp.Store(time.Now().In(cfg.timeZoneLocation).Format(cfg.timeFormat))
}
}()
}
Expand All @@ -83,7 +84,7 @@ func New(opts ...Option) app.HandlerFunc {
return buf.WriteString(pid)
}
Tags[TagTime] = func(ctx context.Context, c *app.RequestContext, buf *bytebufferpool.ByteBuffer) (int, error) {
return buf.WriteString(timestamp)
return buf.WriteString(timestamp.Load().(string))
}

return func(ctx context.Context, c *app.RequestContext) {
Expand Down

0 comments on commit 4157873

Please sign in to comment.