4
4
"bufio"
5
5
"io"
6
6
"runtime"
7
- "strings"
8
7
)
9
8
10
9
// Writer at INFO level. See WriterLevel for details.
@@ -21,18 +20,15 @@ func (logger *Logger) WriterLevel(level Level) *io.PipeWriter {
21
20
return NewEntry (logger ).WriterLevel (level )
22
21
}
23
22
24
- // Writer returns an io.Writer that writes to the logger at the info log level
25
23
func (entry * Entry ) Writer () * io.PipeWriter {
26
24
return entry .WriterLevel (InfoLevel )
27
25
}
28
26
29
- // WriterLevel returns an io.Writer that writes to the logger at the given log level
30
27
func (entry * Entry ) WriterLevel (level Level ) * io.PipeWriter {
31
28
reader , writer := io .Pipe ()
32
29
33
30
var printFunc func (args ... interface {})
34
31
35
- // Determine which log function to use based on the specified log level
36
32
switch level {
37
33
case TraceLevel :
38
34
printFunc = entry .Trace
@@ -52,51 +48,23 @@ func (entry *Entry) WriterLevel(level Level) *io.PipeWriter {
52
48
printFunc = entry .Print
53
49
}
54
50
55
- // Start a new goroutine to scan the input and write it to the logger using the specified print function.
56
- // It splits the input into chunks of up to 64KB to avoid buffer overflows.
57
51
go entry .writerScanner (reader , printFunc )
58
-
59
- // Set a finalizer function to close the writer when it is garbage collected
60
52
runtime .SetFinalizer (writer , writerFinalizer )
61
53
62
54
return writer
63
55
}
64
56
65
- // writerScanner scans the input from the reader and writes it to the logger
66
57
func (entry * Entry ) writerScanner (reader * io.PipeReader , printFunc func (args ... interface {})) {
67
58
scanner := bufio .NewScanner (reader )
68
-
69
- // Set the buffer size to the maximum token size to avoid buffer overflows
70
- scanner .Buffer (make ([]byte , bufio .MaxScanTokenSize ), bufio .MaxScanTokenSize )
71
-
72
- // Define a split function to split the input into chunks of up to 64KB
73
- chunkSize := 64 * 1024 // 64KB
74
- splitFunc := func (data []byte , atEOF bool ) (int , []byte , error ) {
75
- if len (data ) > chunkSize {
76
- return chunkSize , data [:chunkSize ], nil
77
- }
78
-
79
- return len (data ), data , nil
80
- }
81
-
82
- //Use the custom split function to split the input
83
- scanner .Split (splitFunc )
84
-
85
- // Scan the input and write it to the logger using the specified print function
86
59
for scanner .Scan () {
87
- printFunc (strings . TrimRight ( scanner .Text (), " \r \n " ))
60
+ printFunc (scanner .Text ())
88
61
}
89
-
90
- // If there was an error while scanning the input, log an error
91
62
if err := scanner .Err (); err != nil {
92
63
entry .Errorf ("Error while reading from Writer: %s" , err )
93
64
}
94
-
95
- // Close the reader when we are done
96
65
reader .Close ()
97
66
}
98
67
99
- // WriterFinalizer is a finalizer function that closes then given writer when it is garbage collected
100
68
func writerFinalizer (writer * io.PipeWriter ) {
101
69
writer .Close ()
102
70
}
0 commit comments