mediocre-go-lib/mlog/mlog_test.go

78 lines
2.0 KiB
Go
Raw Normal View History

package mlog
import (
"bytes"
"context"
"fmt"
"strings"
. "testing"
"time"
"github.com/mediocregopher/mediocre-go-lib/mctx"
2018-07-18 23:01:28 +00:00
"github.com/mediocregopher/mediocre-go-lib/mtest/massert"
)
func TestTruncate(t *T) {
massert.Require(t,
2018-07-19 18:19:26 +00:00
massert.Equal("abc", Truncate("abc", 4)),
massert.Equal("abc", Truncate("abc", 3)),
massert.Equal("ab...", Truncate("abc", 2)),
)
}
2018-07-19 18:19:26 +00:00
func TestLogger(t *T) {
buf := new(bytes.Buffer)
now := time.Now().UTC()
td, ts := now.Format(msgTimeFormat), fmt.Sprint(now.UnixNano())
l := NewLogger(&LoggerOpts{
MessageHandler: NewMessageHandler(buf),
Now: func() time.Time { return now },
})
2018-07-19 18:19:26 +00:00
assertOut := func(expected string) massert.Assertion {
expected = strings.ReplaceAll(expected, "<TD>", td)
expected = strings.ReplaceAll(expected, "<TS>", ts)
out, err := buf.ReadString('\n')
2018-07-19 18:19:26 +00:00
return massert.All(
massert.Nil(err),
massert.Equal(expected, strings.TrimSpace(out)),
2018-07-19 18:19:26 +00:00
)
}
ctx := context.Background()
// Default max level should be INFO
l.Debug(ctx, "foo")
l.Info(ctx, "bar")
l.Warn(ctx, "baz")
l.Error(ctx, "buz")
massert.Require(t,
assertOut(`{"td":"<TD>","ts":<TS>,"level":"INFO","descr":"bar","level_int":30}`),
assertOut(`{"td":"<TD>","ts":<TS>,"level":"WARN","descr":"baz","level_int":20}`),
assertOut(`{"td":"<TD>","ts":<TS>,"level":"ERROR","descr":"buz","level_int":10}`),
)
// annotate context
ctx = mctx.Annotate(ctx, "foo", "bar")
l.Info(ctx, "bar")
massert.Require(t,
assertOut(`{"td":"<TD>","ts":<TS>,"level":"INFO","descr":"bar","level_int":30,"annotations":{"foo":"bar"}}`),
)
// add other annotations
l.Info(ctx, "bar", mctx.Annotations{
"foo": "BAR",
})
massert.Require(t,
assertOut(`{"td":"<TD>","ts":<TS>,"level":"INFO","descr":"bar","level_int":30,"annotations":{"foo":"BAR"}}`),
)
// add namespace
l = l.WithNamespace("ns")
l.Info(ctx, "bar")
massert.Require(t,
assertOut(`{"td":"<TD>","ts":<TS>,"level":"INFO","ns":["ns"],"descr":"bar","level_int":30,"annotations":{"foo":"bar"}}`),
)
2018-07-18 23:01:28 +00:00
}