-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
JellyTony
committed
Mar 24, 2024
1 parent
de50433
commit 1b19d76
Showing
1 changed file
with
66 additions
and
0 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
package logtest | ||
|
||
import ( | ||
"bytes" | ||
"encoding/json" | ||
"io" | ||
"testing" | ||
|
||
"github.com/nextmicro/logger" | ||
) | ||
|
||
type Buffer struct { | ||
buf *bytes.Buffer | ||
t *testing.T | ||
} | ||
|
||
func Discard(t *testing.T) { | ||
logger.DefaultLogger = logger.New(logger.WithWriter(io.Discard)) | ||
} | ||
|
||
func NewCollector(t *testing.T) *Buffer { | ||
var buf bytes.Buffer | ||
logger.DefaultLogger = logger.New(logger.WithWriter(&buf)) | ||
|
||
t.Cleanup(func() { | ||
logger.Sync() | ||
}) | ||
|
||
return &Buffer{ | ||
buf: &buf, | ||
t: t, | ||
} | ||
} | ||
|
||
func (b *Buffer) Bytes() []byte { | ||
return b.buf.Bytes() | ||
} | ||
|
||
func (b *Buffer) Content() string { | ||
var m map[string]interface{} | ||
if err := json.Unmarshal(b.buf.Bytes(), &m); err != nil { | ||
return "" | ||
} | ||
|
||
content, ok := m["content"] | ||
if !ok { | ||
return "" | ||
} | ||
|
||
switch val := content.(type) { | ||
case string: | ||
return val | ||
default: | ||
// err is impossible to be not nil, unmarshaled from b.buf.Bytes() | ||
bs, _ := json.Marshal(content) | ||
return string(bs) | ||
} | ||
} | ||
|
||
func (b *Buffer) Reset() { | ||
b.buf.Reset() | ||
} | ||
|
||
func (b *Buffer) String() string { | ||
return b.buf.String() | ||
} |