From 63273738cc32ba818ad71325631c22ce7a9b17c1 Mon Sep 17 00:00:00 2001 From: tycho garen Date: Mon, 8 Feb 2021 10:36:21 -0500 Subject: [PATCH] feat: add testing logger --- send/testing.go | 50 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 send/testing.go diff --git a/send/testing.go b/send/testing.go new file mode 100644 index 0000000..1ee97f4 --- /dev/null +++ b/send/testing.go @@ -0,0 +1,50 @@ +package send + +import ( + "testing" + + "github.com/cdr/grip/level" + "github.com/cdr/grip/message" +) + +type testLogger struct { + t *testing.T + *Base +} + +// NewTesting constructs a fully configured Sender implementation that +// logs using the testing.T's logging facility for better integration +// with unit tests. Construct and register such a sender for +// grip.Journaler instances that you use inside of tests to have +// logging that correctly respects go test's verbosity. +// +// By default, this constructor creates a sender with a level threshold +// of "debug" and a default log level of "info." +func NewTesting(t *testing.T) Sender { + return MakeTesting(t, t.Name(), LevelInfo{Threshold: level.Debug, Default: level.Info}) +} + +// MakeTesting produces a sender implementation that logs using the +// testing.T's logging facility for better integration with unit +// tests. Construct and register such a sender for grip.Journaler +// instances that you use inside of tests to have logging that +// correctly respects go test's verbosity. +func MakeTesting(t *testing.T, name string, l LevelInfo) Sender { + s, err := setup(&testLogger{t: t, Base: NewBase(name)}, name, l) + if err != nil { + t.Fatalf("problem setting up logger %s: %v", name, err) + } + return s +} + +func (s *testLogger) Send(m message.Composer) { + if s.Level().ShouldLog(m) { + out, err := s.formatter(m) + if err != nil { + s.t.Logf("formating message [type=%T]: %v", m, err) + return + } + + s.t.Log(out) + } +}