zen/core/zlog/buffer.go

49 lines
875 B
Go
Raw Normal View History

2024-08-23 10:18:27 +07:00
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{
2024-08-23 12:29:47 +07:00
buf: buf,
2024-08-23 10:18:27 +07:00
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 {
2024-08-23 12:29:47 +07:00
buf *bytes.Buffer
2024-08-23 10:18:27 +07:00
pool *jsonHandlerPool
*slog.JSONHandler
}
func (j *jsonHandler) Put() {
// Only put back to pool if buffer is smaller than 4MB in RAM size.
2024-08-23 12:29:47 +07:00
if j.buf.Cap() < 1024*1024*4 {
j.buf.Reset()
2024-08-23 10:18:27 +07:00
j.pool.Put(j)
}
}