Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use sync.Pool and bytes.Buffer for Logger.With perf improvement #594

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 19 additions & 6 deletions log.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@
package zerolog

import (
"bytes"
"context"
"errors"
"fmt"
Expand All @@ -122,8 +123,15 @@ import (
"os"
"strconv"
"strings"
"sync"
)

var contextBufPool = &sync.Pool{
New: func() interface{} {
return bytes.NewBuffer(make([]byte, 0, 500))
},
}

// Level defines log levels.
type Level int8

Expand Down Expand Up @@ -278,15 +286,18 @@ func (l Logger) Output(w io.Writer) Logger {

// With creates a child logger with the field added to its context.
func (l Logger) With() Context {
context := l.context
l.context = make([]byte, 0, 500)
if context != nil {
l.context = append(l.context, context...)
buf := contextBufPool.Get().(*bytes.Buffer)
ctx := l.context
if ctx != nil {
buf.Write(ctx)
} else {
// This is needed for AppendKey to not check len of input
// thus making it inlinable
l.context = enc.AppendBeginMarker(l.context)
buf.Write(enc.AppendBeginMarker(buf.Bytes()))
}
l.context = buf.Bytes()
buf.Reset()
contextBufPool.Put(buf)
return Context{l}
}

Expand All @@ -299,7 +310,9 @@ func (l *Logger) UpdateContext(update func(c Context) Context) {
return
}
if cap(l.context) == 0 {
l.context = make([]byte, 0, 500)
buf := contextBufPool.Get().(*bytes.Buffer)
l.context = buf.Bytes()
contextBufPool.Put(buf)
}
if len(l.context) == 0 {
l.context = enc.AppendBeginMarker(l.context)
Expand Down
Loading