mox/moxio/trace.go

59 lines
1.4 KiB
Go
Raw Normal View History

2023-01-30 16:27:06 +03:00
package moxio
import (
"io"
"github.com/mjl-/mox/mlog"
)
type TraceWriter struct {
2023-01-30 16:27:06 +03:00
log *mlog.Log
prefix string
w io.Writer
level mlog.Level
2023-01-30 16:27:06 +03:00
}
// 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}
2023-01-30 16:27:06 +03:00
}
// 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))
2023-01-30 16:27:06 +03:00
return w.w.Write(buf)
}
func (w *TraceWriter) SetTrace(level mlog.Level) {
w.level = level
}
type TraceReader struct {
2023-01-30 16:27:06 +03:00
log *mlog.Log
prefix string
r io.Reader
level mlog.Level
2023-01-30 16:27:06 +03:00
}
// 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}
2023-01-30 16:27:06 +03:00
}
// 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) {
2023-01-30 16:27:06 +03:00
n, err := r.r.Read(buf)
if n > 0 {
r.log.Trace(r.level, r.prefix+string(buf[:n]))
2023-01-30 16:27:06 +03:00
}
return n, err
}
func (r *TraceReader) SetTrace(level mlog.Level) {
r.level = level
}