Skip to content
This repository has been archived by the owner on May 8, 2024. It is now read-only.

Commit

Permalink
fix: fix field pool bug
Browse files Browse the repository at this point in the history
  • Loading branch information
thinkgos committed Apr 15, 2024
1 parent cbdf1ca commit 1be58d5
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 14 deletions.
10 changes: 5 additions & 5 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,13 +181,13 @@ func (l *Log) Logx(ctx context.Context, level Level, msg string, fields ...Field
if len(l.fn) == 0 {
l.log.Log(level, msg, fields...)
} else {
tmpFields := fieldPool.Get()
defer fieldPool.Put(tmpFields)
fc := defaultFieldPool.Get()
defer defaultFieldPool.Put(fc)
for _, f := range l.fn {
tmpFields = append(tmpFields, f(ctx))
fc.Fields = append(fc.Fields, f(ctx))
}
tmpFields = append(tmpFields, fields...)
l.log.Log(level, msg, tmpFields...)
fc.Fields = append(fc.Fields, fields...)
l.log.Log(level, msg, fc.Fields...)
}
}

Expand Down
23 changes: 14 additions & 9 deletions pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,31 @@ import (
"go.uber.org/zap"
)

var fieldPool = newFieldPool()
var defaultFieldPool = newFieldPool()

type innerFieldPool struct {
type fieldContainer struct {
Fields []Field
}

type fieldPool struct {
pool sync.Pool
}

func newFieldPool() *innerFieldPool {
return &innerFieldPool{
func newFieldPool() *fieldPool {
return &fieldPool{
pool: sync.Pool{
New: func() any {
return make([]zap.Field, 0, 16)
return &fieldContainer{make([]zap.Field, 0, 16)}
},
},
}
}

func (p *innerFieldPool) Get() []zap.Field {
return p.pool.Get().([]zap.Field)
func (p *fieldPool) Get() *fieldContainer {
return p.pool.Get().(*fieldContainer)
}

func (p *innerFieldPool) Put(fields []zap.Field) {
p.pool.Put(fields)
func (p *fieldPool) Put(c *fieldContainer) {
c.Fields = c.Fields[:0]
p.pool.Put(c)
}

0 comments on commit 1be58d5

Please sign in to comment.