-
Notifications
You must be signed in to change notification settings - Fork 23
/
logger_test.go
77 lines (65 loc) · 1.72 KB
/
logger_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package logging
import (
"errors"
"fmt"
"github.com/hhkbp2/testify/require"
"testing"
"time"
)
var (
ErrorTimeout = errors.New("timeout")
)
type MockHandler struct {
*BaseHandler
emitChan chan *LogRecord
t *testing.T
}
func NewMockHandler(t *testing.T) *MockHandler {
object := &MockHandler{
BaseHandler: NewBaseHandler("", LevelDebug),
emitChan: make(chan *LogRecord, 100),
}
Closer.AddHandler(object)
return object
}
func (self *MockHandler) Emit(record *LogRecord) error {
self.emitChan <- record
return nil
}
func (self *MockHandler) Handle(record *LogRecord) int {
return self.BaseHandler.Handle2(self, record)
}
func (self *MockHandler) HandleError(record *LogRecord, err error) {
require.True(self.t, false, "should not be any error")
}
func (self *MockHandler) GetEmitOnTimeout(
timeout time.Duration) (record *LogRecord, err error) {
select {
case record = <-self.emitChan:
return record, nil
case <-time.After(timeout):
return nil, ErrorTimeout
}
}
func TestLoggerLogToHandler(t *testing.T) {
defer Shutdown()
logger := GetLogger("b")
logger.SetLevel(LevelDebug)
require.Equal(t, 0, len(logger.GetHandlers()))
handler := NewMockHandler(t)
logger.AddHandler(handler)
require.Equal(t, 1, len(logger.GetHandlers()))
// test format log
message := "abcd"
format := "msg: %s"
logger.Debugf(format, message)
record, err := handler.GetEmitOnTimeout(time.Second * 0)
require.Nil(t, err)
require.Equal(t, fmt.Sprintf(format, message), record.GetMessage())
// test default format for operand
testError := fmt.Errorf("Example error")
logger.Debug(testError)
record, err = handler.GetEmitOnTimeout(time.Second * 0)
require.Nil(t, err)
require.Equal(t, testError.Error(), record.GetMessage())
}