-
Notifications
You must be signed in to change notification settings - Fork 154
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add PrettyPrintf method to ObservedLogs to logger.NewTesting
ObservedLogs.PrettyPrintf is a helper function to pretty print the logs in the observedLogs
- Loading branch information
Showing
3 changed files
with
69 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package logger | ||
|
||
import ( | ||
"fmt" | ||
"strings" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func TestObservedLogs_PrettyPrintf(t *testing.T) { | ||
want := ` | ||
[debug] a debug message | ||
[debug] a debug message with keys key2=42 | ||
[info] an info message | ||
[info] an info message with keys key1=value1 | ||
[warn] a warn message | ||
[warn] a warn message with keys key2=42 | ||
[error] an error message | ||
[error] an error message with keys key1=value1 | ||
` | ||
|
||
logger, obs := NewTesting("testLogger") | ||
|
||
logger.Debug("a debug message") | ||
logger.Debugw("a debug message with keys", "key2", 42) | ||
logger.Infow("an info message") | ||
logger.Infow("an info message with keys", "key1", "value1") | ||
logger.Warn("a warn message") | ||
logger.Warnw("a warn message with keys", "key2", 42) | ||
logger.Error("an error message") | ||
logger.Errorw("an error message with keys", "key1", "value1") | ||
|
||
var got strings.Builder | ||
printFn := func(a ...any) { | ||
_, _ = fmt.Fprintln(&got, a...) | ||
} | ||
|
||
obs.PrettyPrintf(printFn) | ||
assert.Equal(t, want[1:], got.String()) | ||
|
||
// second call should be empty because PrettyPrintf should consume all logs | ||
got.Reset() | ||
obs.PrettyPrintf(printFn) | ||
assert.Empty(t, got.String()) | ||
} |