-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmock.go
110 lines (88 loc) · 2.33 KB
/
mock.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package ctxd
import (
"bytes"
"context"
"encoding/json"
"sync"
"time"
)
// LoggerMock logs messages to internal buffer.
type LoggerMock struct {
OnError func(err error)
sync.Mutex
bytes.Buffer
LoggedEntries []struct {
Time time.Time `json:"time"`
Level string `json:"level"`
Message string `json:"message"`
Data map[string]interface{} `json:"data,omitempty"`
}
}
func (m *LoggerMock) failed(err error) bool {
if err == nil {
return false
}
if m.OnError != nil {
m.OnError(err)
return true
}
_, _ = m.WriteString(err.Error() + "\n")
return true
}
func (m *LoggerMock) log(ctx context.Context, level, msg string, keysAndValues []interface{}) {
m.Lock()
defer m.Unlock()
data := Tuples(append(Fields(ctx), keysAndValues...)).Fields()
jm, err := json.Marshal(data)
if m.failed(err) {
return
}
m.LoggedEntries = append(m.LoggedEntries, struct {
Time time.Time `json:"time"`
Level string `json:"level"`
Message string `json:"message"`
Data map[string]interface{} `json:"data,omitempty"`
}{Time: time.Now(), Level: level, Message: msg, Data: data})
out := LogWriter(ctx)
if out == nil {
out = m
}
if IsDebug(ctx) {
_, err = out.Write([]byte("debug mode, "))
if m.failed(err) {
return
}
}
_, err = out.Write([]byte(level + ": " + msg + " "))
if m.failed(err) {
return
}
_, err = out.Write(jm)
if m.failed(err) {
return
}
_, err = out.Write([]byte("\n"))
if m.failed(err) {
return
}
}
// Debug logs a message.
func (m *LoggerMock) Debug(ctx context.Context, msg string, keysAndValues ...interface{}) {
m.log(ctx, "debug", msg, keysAndValues)
}
// Info logs a message.
func (m *LoggerMock) Info(ctx context.Context, msg string, keysAndValues ...interface{}) {
m.log(ctx, "info", msg, keysAndValues)
}
// Important logs a message.
func (m *LoggerMock) Important(ctx context.Context, msg string, keysAndValues ...interface{}) {
m.log(ctx, "important", msg, keysAndValues)
}
// Warn logs a message.
func (m *LoggerMock) Warn(ctx context.Context, msg string, keysAndValues ...interface{}) {
m.log(ctx, "warn", msg, keysAndValues)
}
// Error logs a message.
func (m *LoggerMock) Error(ctx context.Context, msg string, keysAndValues ...interface{}) {
m.log(ctx, "error", msg, keysAndValues)
}