-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
writer_test.go
98 lines (83 loc) · 2.4 KB
/
writer_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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package logrus_test
import (
"bufio"
"bytes"
"log"
"net/http"
"strings"
"testing"
"time"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
)
func ExampleLogger_Writer_httpServer() {
logger := logrus.New()
w := logger.Writer()
defer w.Close()
srv := http.Server{
// create a stdlib log.Logger that writes to
// logrus.Logger.
ErrorLog: log.New(w, "", 0),
}
if err := srv.ListenAndServe(); err != nil {
logger.Fatal(err)
}
}
func ExampleLogger_Writer_stdlib() {
logger := logrus.New()
logger.Formatter = &logrus.JSONFormatter{}
// Use logrus for standard log output
// Note that `log` here references stdlib's log
// Not logrus imported under the name `log`.
log.SetOutput(logger.Writer())
}
func TestWriterSplitNewlines(t *testing.T) {
buf := bytes.NewBuffer(nil)
logger := logrus.New()
logger.Formatter = &logrus.TextFormatter{
DisableColors: true,
DisableTimestamp: true,
}
logger.SetOutput(buf)
writer := logger.Writer()
const logNum = 10
for i := 0; i < logNum; i++ {
_, err := writer.Write([]byte("bar\nfoo\n"))
assert.NoError(t, err, "writer.Write failed")
}
writer.Close()
// Test is flaky because it writes in another goroutine,
// we need to make sure to wait a bit so all write are done.
time.Sleep(500 * time.Millisecond)
lines := strings.Split(strings.TrimRight(buf.String(), "\n"), "\n")
assert.Len(t, lines, logNum*2, "logger printed incorrect number of lines")
}
func TestWriterSplitsMax64KB(t *testing.T) {
buf := bytes.NewBuffer(nil)
logger := logrus.New()
logger.Formatter = &logrus.TextFormatter{
DisableColors: true,
DisableTimestamp: true,
}
logger.SetOutput(buf)
writer := logger.Writer()
// write more than 64KB
const bigWriteLen = bufio.MaxScanTokenSize + 100
output := make([]byte, bigWriteLen)
// lets not write zero bytes
for i := 0; i < bigWriteLen; i++ {
output[i] = 'A'
}
for i := 0; i < 3; i++ {
len, err := writer.Write(output)
assert.NoError(t, err, "writer.Write failed")
assert.Equal(t, bigWriteLen, len, "bytes written")
}
writer.Close()
// Test is flaky because it writes in another goroutine,
// we need to make sure to wait a bit so all write are done.
time.Sleep(500 * time.Millisecond)
lines := strings.Split(strings.TrimRight(buf.String(), "\n"), "\n")
// we should have 4 lines because we wrote more than 64 KB each time
assert.Len(t, lines, 4, "logger printed incorrect number of lines")
}