Skip to content

Commit

Permalink
Optimize memory allocation.
Browse files Browse the repository at this point in the history
  • Loading branch information
edoger committed Apr 28, 2021
1 parent 3a31236 commit c1de7f9
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 12 deletions.
15 changes: 4 additions & 11 deletions log.go
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,6 @@ type log struct {
ctx context.Context
fields internal.Fields
caller *internal.CallerReporter
root bool // In the top level logger?
}

// Name returns the logger name.
Expand All @@ -263,7 +262,7 @@ func (o *log) Name() string {

// WithField adds the given extended data to the log.
func (o *log) WithField(key string, value interface{}) Log {
if o.root {
if len(o.fields) == 0 {
return &log{core: o.core, fields: internal.Fields{key: value}, ctx: o.ctx, caller: o.caller}
}
r := &log{core: o.core, fields: o.fields.Clone(1), ctx: o.ctx, caller: o.caller}
Expand All @@ -279,18 +278,15 @@ func (o *log) WithError(err error) Log {

// WithFields adds the given multiple extended data to the log.
func (o *log) WithFields(fields map[string]interface{}) Log {
if o.root {
if len(o.fields) == 0 {
return &log{core: o.core, fields: internal.MakeFields(fields), ctx: o.ctx, caller: o.caller}
}
return &log{core: o.core, fields: o.fields.With(fields), ctx: o.ctx, caller: o.caller}
}

// WithContext adds the given context to the log.
func (o *log) WithContext(ctx context.Context) Log {
if o.root {
return &log{core: o.core, ctx: ctx, caller: o.caller}
}
return &log{core: o.core, fields: o.fields.Clone(0), ctx: ctx, caller: o.caller}
return &log{core: o.core, fields: o.fields, ctx: ctx, caller: o.caller}
}

// WithCaller forces the caller report of the current log to be enabled.
Expand All @@ -303,10 +299,7 @@ func (o *log) WithCaller(skip ...int) Log {
if o.caller != nil && o.caller.Equal(n) {
return o
}
if o.root {
return &log{core: o.core, ctx: o.ctx, caller: internal.NewCallerReporter(n)}
}
return &log{core: o.core, fields: o.fields.Clone(0), ctx: o.ctx, caller: internal.NewCallerReporter(n)}
return &log{core: o.core, fields: o.fields, ctx: o.ctx, caller: internal.NewCallerReporter(n)}
}

// Format and record the current log.
Expand Down
2 changes: 1 addition & 1 deletion logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ type Logger interface {
// New creates a new Logger instance.
// By default, the logger level is TraceLevel and logs will be output to os.Stdout.
func New(name string) Logger {
return &logger{log{core: newCore(name), root: true}}
return &logger{log{core: newCore(name)}}
}

// The logger type is an implementation of the built-in logger interface.
Expand Down

0 comments on commit c1de7f9

Please sign in to comment.