-
Notifications
You must be signed in to change notification settings - Fork 109
/
trace.go
58 lines (48 loc) · 1.37 KB
/
trace.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
package moxio
import (
"io"
"github.com/mjl-/mox/mlog"
)
type TraceWriter struct {
log *mlog.Log
prefix string
w io.Writer
level mlog.Level
}
// NewTraceWriter wraps "w" into a writer that logs all writes to "log" with
// log level trace, prefixed with "prefix".
func NewTraceWriter(log *mlog.Log, prefix string, w io.Writer) *TraceWriter {
return &TraceWriter{log, prefix, w, mlog.LevelTrace}
}
// Write logs a trace line for writing buf to the client, then writes to the
// client.
func (w *TraceWriter) Write(buf []byte) (int, error) {
w.log.Trace(w.level, w.prefix+string(buf))
return w.w.Write(buf)
}
func (w *TraceWriter) SetTrace(level mlog.Level) {
w.level = level
}
type TraceReader struct {
log *mlog.Log
prefix string
r io.Reader
level mlog.Level
}
// NewTraceReader wraps reader "r" into a reader that logs all reads to "log"
// with log level trace, prefixed with "prefix".
func NewTraceReader(log *mlog.Log, prefix string, r io.Reader) *TraceReader {
return &TraceReader{log, prefix, r, mlog.LevelTrace}
}
// Read does a single Read on its underlying reader, logs data of successful
// reads, and returns the data read.
func (r *TraceReader) Read(buf []byte) (int, error) {
n, err := r.r.Read(buf)
if n > 0 {
r.log.Trace(r.level, r.prefix+string(buf[:n]))
}
return n, err
}
func (r *TraceReader) SetTrace(level mlog.Level) {
r.level = level
}