Skip to content

Commit 1e99b62

Browse files
author
Matthew Fisher
committed
feat(log): add SetStdout() and SetStderr()
This new feature allows users to change the Stdout and Stderr writers for the DefaultLogger on-the-fly, allowing them to test log output based on certain input from the user.
1 parent 189ed6b commit 1e99b62

2 files changed

Lines changed: 26 additions & 1 deletion

File tree

log/log.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,11 +53,21 @@ func NewLogger(stdout, stderr io.Writer, debug bool) *Logger {
5353
// DefaultLogger is the default logging implementation. It's used in all top level funcs inside the log package, and represents the equivalent of NewLogger(os.Stdout, os.Stderr)
5454
var DefaultLogger = &Logger{stdout: os.Stdout, stderr: os.Stderr, debug: false}
5555

56-
// SetDebug sets the internal debugging field on or off. This func is not concurrency safe
56+
// SetDebug sets the internal debugging field on or off. This func is not concurrency safe.
5757
func (l *Logger) SetDebug(debug bool) {
5858
l.debug = debug
5959
}
6060

61+
// SetStdout sets the internal stdout writer. This func is not concurrency safe.
62+
func (l *Logger) SetStdout(w io.Writer) {
63+
l.stdout = w
64+
}
65+
66+
// SetStderr sets the internal stderr writer. This func is not concurrency safe.
67+
func (l *Logger) SetStderr(w io.Writer) {
68+
l.stderr = w
69+
}
70+
6171
// Msg passes through the formatter, but otherwise prints exactly as-is.
6272
//
6373
// No prettification.

log/log_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,18 @@ func TestAppendNewLine(t *testing.T) {
6464
newStr := appendNewLine(str)
6565
assert.Equal(t, newStr, str+"\n", "new string")
6666
}
67+
68+
func TestDefaultLoggerSetStdout(t *testing.T) {
69+
var b bytes.Buffer
70+
DefaultLogger.SetStdout(&b)
71+
Warn("hello world")
72+
assert.Equal(t, b.String(), "hello world\n", "stdout output")
73+
}
74+
75+
func TestDefaultLoggerSetStderr(t *testing.T) {
76+
var b bytes.Buffer
77+
DefaultLogger.SetStderr(&b)
78+
DefaultLogger.SetDebug(true)
79+
Debug("hello world")
80+
assert.Equal(t, b.String(), addColor(DebugPrefix+" ", Cyan), "stderr output")
81+
}

0 commit comments

Comments
 (0)