Skip to content

Commit

Permalink
chore: add test for logger
Browse files Browse the repository at this point in the history
  • Loading branch information
alecthomas committed Jul 25, 2024
1 parent bbe565d commit a68383b
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
9 changes: 6 additions & 3 deletions internal/log/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"runtime"
"time"

"github.com/benbjohnson/clock"
"golang.org/x/exp/maps"
)

Expand All @@ -29,6 +30,7 @@ type Logger struct {
level Level
attributes map[string]string
sink Sink
clock clock.Clock
}

// New returns a new logger.
Expand All @@ -37,6 +39,7 @@ func New(level Level, sink Sink) *Logger {
level: level,
attributes: map[string]string{},
sink: sink,
clock: clock.New(),
}
}

Expand Down Expand Up @@ -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
Expand Down
33 changes: 33 additions & 0 deletions internal/log/logger_test.go
Original file line number Diff line number Diff line change
@@ -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())
}

0 comments on commit a68383b

Please sign in to comment.