-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtesting_logger.go
108 lines (95 loc) · 2.11 KB
/
testing_logger.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
package tower
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"sync"
)
type TestingJSONLogger struct {
buf *bytes.Buffer
mu sync.Mutex
}
func NewTestingTower(service Service) (*Tower, *TestingJSONLogger) {
t := NewTower(service)
logger := NewTestingJSONLogger()
t.logger = logger
return t, logger
}
// NewTestingJSONLogger returns a very basic logger for testing purposes.
func NewTestingJSONLogger() *TestingJSONLogger {
return &TestingJSONLogger{
buf: new(bytes.Buffer),
}
}
// Log implements tower.Logger.
func (t *TestingJSONLogger) Log(ctx context.Context, entry Entry) {
t.mu.Lock()
defer t.mu.Unlock()
err := json.NewEncoder(t.buf).Encode(entry)
if err != nil {
t.buf.WriteString(err.Error())
}
}
// LogError implements tower.Logger.
func (t *TestingJSONLogger) LogError(ctx context.Context, err Error) {
t.mu.Lock()
defer t.mu.Unlock()
errJson := json.NewEncoder(t.buf).Encode(err)
if errJson != nil {
t.buf.WriteString(errJson.Error())
}
}
// Reset resets the buffer to be empty.
func (t *TestingJSONLogger) Reset() {
t.mu.Lock()
defer t.mu.Unlock()
t.buf.Reset()
}
// String returns the accumulated bytes as string.
func (t *TestingJSONLogger) String() string {
t.mu.Lock()
defer t.mu.Unlock()
return t.buf.String()
}
// Bytes returns the accumulated bytes.
func (t *TestingJSONLogger) Bytes() []byte {
t.mu.Lock()
defer t.mu.Unlock()
cp := make([]byte, t.buf.Len())
copy(cp, t.buf.Bytes())
return cp
}
func (t *TestingJSONLogger) MarshalJSON() ([]byte, error) {
t.mu.Lock()
defer t.mu.Unlock()
out := make([]json.RawMessage, 0, 4)
scanner := bufio.NewScanner(t.buf)
for scanner.Scan() {
out = append(out, json.RawMessage(scanner.Text()))
}
if len(out) == 1 {
return out[0], nil
}
return json.Marshal(out)
}
func (t *TestingJSONLogger) PrettyPrint() {
t.mu.Lock()
defer t.mu.Unlock()
var out bytes.Buffer
scanner := bufio.NewScanner(t.buf)
i := 0
for scanner.Scan() {
if i > 0 {
out.WriteString("\n")
}
err := json.Indent(&out, scanner.Bytes(), "", " ")
if err != nil {
fmt.Println(err.Error())
return
}
i++
}
fmt.Println(out.String())
}