diff --git a/internal/log/logger.go b/internal/log/logger.go index 99aaf4cc68..07aac3fe9a 100644 --- a/internal/log/logger.go +++ b/internal/log/logger.go @@ -8,6 +8,7 @@ import ( "runtime" "time" + "github.com/benbjohnson/clock" "golang.org/x/exp/maps" ) @@ -29,6 +30,7 @@ type Logger struct { level Level attributes map[string]string sink Sink + clock clock.Clock } // New returns a new logger. @@ -37,6 +39,7 @@ func New(level Level, sink Sink) *Logger { level: level, attributes: map[string]string{}, sink: sink, + clock: clock.New(), } } @@ -72,11 +75,11 @@ func (l *Logger) Log(entry Entry) { return } if entry.Time.IsZero() { - entry.Time = time.Now() + // Use UTC now + entry.Time = l.clock.Now().UTC() } - // merge logger and entry attributes - mergedAttributes := make(map[string]string) + mergedAttributes := make(map[string]string, len(l.attributes)+len(entry.Attributes)) maps.Copy(mergedAttributes, l.attributes) maps.Copy(mergedAttributes, entry.Attributes) entry.Attributes = mergedAttributes diff --git a/internal/log/logger_test.go b/internal/log/logger_test.go new file mode 100644 index 0000000000..7af86da748 --- /dev/null +++ b/internal/log/logger_test.go @@ -0,0 +1,33 @@ +package log + +import ( + "errors" + "strings" + "testing" + + "github.com/alecthomas/assert/v2" + "github.com/benbjohnson/clock" +) + +func TestLogger(t *testing.T) { + w := &strings.Builder{} + log := New(Trace, newJSONSink(w)) + log.clock = clock.NewMock() + log.Tracef("trace: %s", "trace") + log.Debugf("debug: %s", "debug") + log.Infof("info: %s", "info") + log.Warnf("warn: %s", "warn") + log.Errorf(errors.New("error"), "error: %s", "error") + log = log.Scope("scoped").Attrs(map[string]string{"key": "value"}) + log.Tracef("trace: %s", "trace") + log.Log(Entry{Level: Trace, Message: "trace: trace"}) + assert.Equal(t, strings.TrimSpace(` +{"level":"trace","message":"trace: trace","time":"1970-01-01T00:00:00Z"} +{"level":"debug","message":"debug: debug","time":"1970-01-01T00:00:00Z"} +{"level":"info","message":"info: info","time":"1970-01-01T00:00:00Z"} +{"level":"warn","message":"warn: warn","time":"1970-01-01T00:00:00Z"} +{"level":"error","message":"error: error: error","time":"1970-01-01T00:00:00Z","error":"error"} +{"level":"trace","attributes":{"key":"value","scope":"scoped"},"message":"trace: trace","time":"1970-01-01T00:00:00Z"} +{"level":"trace","attributes":{"key":"value","scope":"scoped"},"message":"trace: trace","time":"1970-01-01T00:00:00Z"} +`)+"\n", w.String()) +}