Skip to content

Commit 6699a89

Browse files
authored
Merge pull request #1145 from sirupsen/custom_buffer_pool
Add an API to plug a custom buffer free item mangement system
2 parents 42baed8 + 64a5944 commit 6699a89

File tree

2 files changed

+57
-9
lines changed

2 files changed

+57
-9
lines changed

buffer_pool.go

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

entry.go

+5-9
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ import (
1313
)
1414

1515
var (
16-
bufferPool *sync.Pool
1716

1817
// qualified package name, cached at first use
1918
logrusPackage string
@@ -31,12 +30,6 @@ const (
3130
)
3231

3332
func init() {
34-
bufferPool = &sync.Pool{
35-
New: func() interface{} {
36-
return new(bytes.Buffer)
37-
},
38-
}
39-
4033
// start at the bottom of the stack before the package-name cache is primed
4134
minimumCallerDepth = 1
4235
}
@@ -243,9 +236,12 @@ func (entry Entry) log(level Level, msg string) {
243236

244237
entry.fireHooks()
245238

246-
buffer = bufferPool.Get().(*bytes.Buffer)
239+
buffer = getBuffer()
240+
defer func() {
241+
entry.Buffer = nil
242+
putBuffer(buffer)
243+
}()
247244
buffer.Reset()
248-
defer bufferPool.Put(buffer)
249245
entry.Buffer = buffer
250246

251247
entry.write()

0 commit comments

Comments
 (0)