Skip to content

Commit

Permalink
fix: move pool to internal
Browse files Browse the repository at this point in the history
  • Loading branch information
thinkgos committed May 21, 2024
1 parent 8f71b01 commit 2a225f7
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 87 deletions.
26 changes: 14 additions & 12 deletions gormzap/gz.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"go.uber.org/zap"
"gorm.io/gorm"
"gorm.io/gorm/logger"

"github.com/things-go/gin-contrib/internal/pool"
)

// Logger logger for gorm2
Expand Down Expand Up @@ -87,8 +89,8 @@ func (l *Logger) Info(ctx context.Context, msg string, args ...any) {
if l.LogLevel >= logger.Info && l.log.Level().Enabled(zap.InfoLevel) {
msg = fmt.Sprintf(msg, args...)
if neeCaller := l.callerCore.caller != nil && l.callerCore.Enabled(zap.InfoLevel); neeCaller || len(l.customFields) > 0 {
fc := poolGet()
defer poolPut(fc)
fc := pool.Get()
defer pool.Put(fc)
for _, customField := range l.customFields {
fc.Fields = append(fc.Fields, customField(ctx))
}
Expand All @@ -107,8 +109,8 @@ func (l *Logger) Warn(ctx context.Context, msg string, args ...any) {
if l.LogLevel >= logger.Warn && l.log.Level().Enabled(zap.WarnLevel) {
msg = fmt.Sprintf(msg, args...)
if neeCaller := l.callerCore.caller != nil && l.callerCore.Enabled(zap.WarnLevel); neeCaller || len(l.customFields) > 0 {
fc := poolGet()
defer poolPut(fc)
fc := pool.Get()
defer pool.Put(fc)
for _, customField := range l.customFields {
fc.Fields = append(fc.Fields, customField(ctx))
}
Expand All @@ -127,8 +129,8 @@ func (l *Logger) Error(ctx context.Context, msg string, args ...any) {
if l.LogLevel >= logger.Error && l.log.Level().Enabled(zap.ErrorLevel) {
msg = fmt.Sprintf(msg, args...)
if neeCaller := l.callerCore.caller != nil && l.callerCore.Enabled(zap.ErrorLevel); neeCaller || len(l.customFields) > 0 {
fc := poolGet()
defer poolPut(fc)
fc := pool.Get()
defer pool.Put(fc)
for _, customField := range l.customFields {
fc.Fields = append(fc.Fields, customField(ctx))
}
Expand All @@ -154,8 +156,8 @@ func (l *Logger) Trace(ctx context.Context, begin time.Time, f func() (string, i
l.LogLevel >= logger.Error &&
l.log.Level().Enabled(zap.ErrorLevel) &&
(!l.IgnoreRecordNotFoundError || !errors.Is(err, gorm.ErrRecordNotFound)):
fc := poolGet()
defer poolPut(fc)
fc := pool.Get()
defer pool.Put(fc)
for _, customField := range l.customFields {
fc.Fields = append(fc.Fields, customField(ctx))
}
Expand All @@ -179,8 +181,8 @@ func (l *Logger) Trace(ctx context.Context, begin time.Time, f func() (string, i
l.SlowThreshold != 0 &&
l.LogLevel >= logger.Warn &&
l.log.Level().Enabled(zap.WarnLevel):
fc := poolGet()
defer poolPut(fc)
fc := pool.Get()
defer pool.Put(fc)
for _, customField := range l.customFields {
fc.Fields = append(fc.Fields, customField(ctx))
}
Expand All @@ -202,8 +204,8 @@ func (l *Logger) Trace(ctx context.Context, begin time.Time, f func() (string, i
fc.Fields = append(fc.Fields, zap.String("sql", sql))
l.log.Warn("trace", fc.Fields...)
case l.LogLevel == logger.Info && l.log.Level().Enabled(zap.InfoLevel):
fc := poolGet()
defer poolPut(fc)
fc := pool.Get()
defer pool.Put(fc)
for _, customField := range l.customFields {
fc.Fields = append(fc.Fields, customField(ctx))
}
Expand Down
54 changes: 0 additions & 54 deletions gormzap/pool.go

This file was deleted.

30 changes: 21 additions & 9 deletions gzap/gzap.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,14 @@ import (
"os"
"runtime/debug"
"strings"
"sync/atomic"
"time"

"github.com/gin-gonic/gin"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"

"github.com/things-go/gin-contrib/internal/pool"
)

// Option logger/recover option
Expand All @@ -42,7 +45,16 @@ func WithSkipLogging(f func(c *gin.Context) bool) Option {
// WithEnableBody optional custom enable request/response body.
func WithEnableBody(b bool) Option {
return func(c *Config) {
c.enableBody = b
c.enableBody.Store(b)
}
}

// WithExternalEnableBody optional custom enable request/response body control by external itself.
func WithExternalEnableBody(b *atomic.Bool) Option {
return func(c *Config) {
if b != nil {
c.enableBody = b
}
}
}

Expand Down Expand Up @@ -121,7 +133,7 @@ type Config struct {
// zap.WarnLevel: when status >= http.StatusBadRequest && status <= http.StatusUnavailableForLegalReasons
// zap.InfoLevel: otherwise.
useLoggerLevel func(c *gin.Context) zapcore.Level
enableBody bool // enable request/response body
enableBody *atomic.Bool // enable request/response body
limit int // <=0: mean not limit
field [fieldMaxLen]string // log field names
}
Expand Down Expand Up @@ -162,7 +174,7 @@ func newConfig() Config {
skipRequestBody: func(c *gin.Context) bool { return false },
skipResponseBody: func(c *gin.Context) bool { return false },
useLoggerLevel: useLoggerLevel,
enableBody: false,
enableBody: &atomic.Bool{},
limit: 0,
field: [fieldMaxLen]string{
"status",
Expand Down Expand Up @@ -192,7 +204,7 @@ func Logger(logger *zap.Logger, opts ...Option) gin.HandlerFunc {
respBodyBuilder := &strings.Builder{}
reqBody := "skip request body"

if cfg.enableBody {
if cfg.enableBody.Load() {
c.Writer = &bodyWriter{ResponseWriter: c.Writer, dupBody: respBodyBuilder}
if hasSkipRequestBody := skipRequestBody(c) || cfg.skipRequestBody(c); !hasSkipRequestBody {
reqBodyBuf, err := io.ReadAll(c.Request.Body)
Expand Down Expand Up @@ -228,8 +240,8 @@ func Logger(logger *zap.Logger, opts ...Option) gin.HandlerFunc {
level = cfg.useLoggerLevel(c)
}

fc := poolGet()
defer poolPut(fc)
fc := pool.Get()
defer pool.Put(fc)
fc.Fields = append(fc.Fields,
zap.Int(cfg.field[FieldStatus], c.Writer.Status()),
zap.String(cfg.field[FieldMethod], c.Request.Method),
Expand All @@ -240,7 +252,7 @@ func Logger(logger *zap.Logger, opts ...Option) gin.HandlerFunc {
zap.String(cfg.field[FieldUserAgent], c.Request.UserAgent()),
zap.Duration(cfg.field[FieldLatency], time.Since(start)),
)
if cfg.enableBody {
if cfg.enableBody.Load() {
respBody := "skip response body"
if hasSkipResponseBody := skipResponseBody(c) || cfg.skipResponseBody(c); !hasSkipResponseBody {
if cfg.limit > 0 && respBodyBuilder.Len() >= cfg.limit {
Expand Down Expand Up @@ -311,8 +323,8 @@ func Recovery(logger *zap.Logger, stack bool, opts ...Option) gin.HandlerFunc {
return
}

fc := poolGet()
defer poolPut(fc)
fc := pool.Get()
defer pool.Put(fc)
fc.Fields = append(fc.Fields,
zap.Any("error", err),
zap.ByteString("request", httpRequest),
Expand Down
24 changes: 12 additions & 12 deletions gzap/pool.go → internal/pool/pool.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package gzap
package pool

import (
"sync"
Expand All @@ -23,30 +23,30 @@ func (c *fieldContainer) reset() *fieldContainer {
return c
}

// poolGet selects an arbitrary item from the field Pool, removes it from the
// Get selects an arbitrary item from the field Pool, removes it from the
// field Pool, and returns it to the caller.
// PoolGet may choose to ignore the field pool and treat it as empty.
// Callers should not assume any relation between values passed to PoolPut and
// the values returned by PoolGet.
// Get may choose to ignore the field pool and treat it as empty.
// Callers should not assume any relation between values passed to Put and
// the values returned by Get.
//
// NOTE: This function should be call PoolPut to give back.
// NOTE: This function should be call Put to give back.
// NOTE: You should know `sync.Pool` work principle
// ```go
//
// fc := logger.PoolGet()
// defer logger.PoolPut(fc)
// fc := logger.Get()
// defer logger.Put(fc)
// fc.Fields = append(fc.Fields, logger.String("k1", "v1"))
// ... use fc.Fields
//
// ```
func poolGet() *fieldContainer {
func Get() *fieldContainer {
c := fieldPool.Get().(*fieldContainer)
return c.reset()
}

// poolPut adds x to the pool.
// NOTE: See PoolGet.
func poolPut(c *fieldContainer) {
// Put adds x to the pool.
// NOTE: See Get.
func Put(c *fieldContainer) {
if c == nil {
return
}
Expand Down

0 comments on commit 2a225f7

Please sign in to comment.