diff --git a/log/README.md b/log/README.md new file mode 100644 index 0000000..84045aa --- /dev/null +++ b/log/README.md @@ -0,0 +1,2 @@ +# logutil +The package contains helpers to interact with logs diff --git a/log/logutil.go b/log/logutil.go new file mode 100644 index 0000000..4f6314e --- /dev/null +++ b/log/logutil.go @@ -0,0 +1,19 @@ +package logutil + +import ( + "io" + "log" + "os" +) + +// DisableDefaultLogger disables the default logger. +func DisableDefaultLogger() { + log.SetFlags(0) + log.SetOutput(io.Discard) +} + +// EnableDefaultLogger enables the default logger. +func EnableDefaultLogger() { + log.SetFlags(log.LstdFlags) + log.SetOutput(os.Stderr) +} diff --git a/log/logutil_test.go b/log/logutil_test.go new file mode 100644 index 0000000..88fc654 --- /dev/null +++ b/log/logutil_test.go @@ -0,0 +1,39 @@ +package logutil + +import ( + "bytes" + "io" + "log" + "os" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestDisableDefaultLogger(t *testing.T) { + msg := "sample test" + buf := new(bytes.Buffer) + log.SetOutput(buf) + DisableDefaultLogger() + log.Print(msg) + require.Equal(t, "", buf.String()) +} + +func TestEnableDefaultLogger(t *testing.T) { + msg := "sample test" + buf := new(bytes.Buffer) + var stderr = *os.Stderr + r, w, _ := os.Pipe() + os.Stderr = w + exit := make(chan bool) + go func() { + _, _ = io.Copy(buf, r) + exit <- true + }() + EnableDefaultLogger() + log.Print(msg) + w.Close() + <-exit + os.Stderr = &stderr + require.Contains(t, buf.String(), msg) +}