zen/core/zlog/buffer.go
2024-08-27 15:22:42 +07:00

49 lines
875 B
Go

package zlog
import (
"bytes"
"log/slog"
"sync"
)
type jsonHandlerPool struct {
*sync.Pool
}
func newJsonHandlerPool(handlerOption *slog.HandlerOptions) *jsonHandlerPool {
var handlerPool *jsonHandlerPool
generator := &sync.Pool{
New: func() any {
buf := new(bytes.Buffer)
return &jsonHandler{
buf: buf,
pool: handlerPool,
JSONHandler: slog.NewJSONHandler(buf, handlerOption),
}
},
}
handlerPool = &jsonHandlerPool{
generator,
}
return handlerPool
}
func (jhp *jsonHandlerPool) Get() *jsonHandler {
handler := jhp.Pool.Get().(*jsonHandler)
return handler
}
type jsonHandler struct {
buf *bytes.Buffer
pool *jsonHandlerPool
*slog.JSONHandler
}
func (j *jsonHandler) Put() {
// Only put back to pool if buffer is smaller than 4MB in RAM size.
if j.buf.Cap() < 1024*1024*4 {
j.buf.Reset()
j.pool.Put(j)
}
}