Skip to content

Commit

Permalink
Add WithTimeSource Option
Browse files Browse the repository at this point in the history
Allow passing current time source.
  • Loading branch information
ernado committed Dec 24, 2020
1 parent a68efdb commit 9479a5b
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
8 changes: 6 additions & 2 deletions logger.go
Expand Up @@ -51,6 +51,9 @@ type Logger struct {
addStack zapcore.LevelEnabler

callerSkip int

// now returns current time, default is time.Now.
now func() time.Time
}

// New constructs a new Logger from the provided zapcore.Core and Options. If
Expand All @@ -71,6 +74,7 @@ func New(core zapcore.Core, options ...Option) *Logger {
core: core,
errorOutput: zapcore.Lock(os.Stderr),
addStack: zapcore.FatalLevel + 1,
now: time.Now,
}
return log.WithOptions(options...)
}
Expand Down Expand Up @@ -270,7 +274,7 @@ func (log *Logger) check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry {
// log message will actually be written somewhere.
ent := zapcore.Entry{
LoggerName: log.name,
Time: time.Now(),
Time: log.now(),
Level: lvl,
Message: msg,
}
Expand Down Expand Up @@ -307,7 +311,7 @@ func (log *Logger) check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry {
if log.addCaller {
frame, defined := getCallerFrame(log.callerSkip + callerSkipOffset)
if !defined {
fmt.Fprintf(log.errorOutput, "%v Logger.check error: failed to get caller\n", time.Now().UTC())
fmt.Fprintf(log.errorOutput, "%v Logger.check error: failed to get caller\n", log.now().UTC())
log.errorOutput.Sync()
}

Expand Down
9 changes: 9 additions & 0 deletions options.go
Expand Up @@ -22,6 +22,7 @@ package zap

import (
"fmt"
"time"

"go.uber.org/zap/zapcore"
)
Expand Down Expand Up @@ -138,3 +139,11 @@ func OnFatal(action zapcore.CheckWriteAction) Option {
log.onFatal = action
})
}

// WithTimeSource configures the Logger to get current time from provided
// function when creating entry.
func WithTimeSource(now func() time.Time) Option {
return optionFunc(func(log *Logger) {
log.now = now
})
}
20 changes: 20 additions & 0 deletions time_source_test.go
@@ -0,0 +1,20 @@
package zap

import (
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/zap/zaptest/observer"
)

func TestWithTimeSource(t *testing.T) {
date := time.Date(2077, 1, 23, 10, 15, 13, 441, time.UTC)
now := func() time.Time { return date }
withLogger(t, DebugLevel, []Option{WithTimeSource(now)}, func(log *Logger, logs *observer.ObservedLogs) {
log.Info("")
require.Equal(t, 1, logs.Len(), "Expected only one log entry to be written.")
assert.Equal(t, date, logs.All()[0].Entry.Time, "Unexpected entry time.")
})
}

0 comments on commit 9479a5b

Please sign in to comment.