buffer_pool.go 797 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package logrus
  2. import (
  3. "bytes"
  4. "sync"
  5. )
  6. var (
  7. bufferPool BufferPool
  8. )
  9. type BufferPool interface {
  10. Put(*bytes.Buffer)
  11. Get() *bytes.Buffer
  12. }
  13. type defaultPool struct {
  14. pool *sync.Pool
  15. }
  16. func (p *defaultPool) Put(buf *bytes.Buffer) {
  17. p.pool.Put(buf)
  18. }
  19. func (p *defaultPool) Get() *bytes.Buffer {
  20. return p.pool.Get().(*bytes.Buffer)
  21. }
  22. func getBuffer() *bytes.Buffer {
  23. return bufferPool.Get()
  24. }
  25. func putBuffer(buf *bytes.Buffer) {
  26. buf.Reset()
  27. bufferPool.Put(buf)
  28. }
  29. // SetBufferPool allows to replace the default logrus buffer pool
  30. // to better meets the specific needs of an application.
  31. func SetBufferPool(bp BufferPool) {
  32. bufferPool = bp
  33. }
  34. func init() {
  35. SetBufferPool(&defaultPool{
  36. pool: &sync.Pool{
  37. New: func() interface{} {
  38. return new(bytes.Buffer)
  39. },
  40. },
  41. })
  42. }