2023-01-30 16:27:06 +03:00
|
|
|
package moxio
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
2024-02-08 16:49:01 +03:00
|
|
|
"log/slog"
|
2023-12-05 15:35:58 +03:00
|
|
|
|
2023-01-30 16:27:06 +03:00
|
|
|
"github.com/mjl-/mox/mlog"
|
|
|
|
)
|
|
|
|
|
2023-02-03 22:33:19 +03:00
|
|
|
type TraceWriter struct {
|
2023-12-05 15:35:58 +03:00
|
|
|
log mlog.Log
|
2023-01-30 16:27:06 +03:00
|
|
|
prefix string
|
|
|
|
w io.Writer
|
2023-12-05 15:35:58 +03:00
|
|
|
level slog.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".
|
2023-12-05 15:35:58 +03:00
|
|
|
func NewTraceWriter(log mlog.Log, prefix string, w io.Writer) *TraceWriter {
|
2023-02-03 22:33:19 +03:00
|
|
|
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.
|
2023-02-03 22:33:19 +03:00
|
|
|
func (w *TraceWriter) Write(buf []byte) (int, error) {
|
2023-12-05 15:35:58 +03:00
|
|
|
w.log.Trace(w.level, w.prefix, buf)
|
2023-01-30 16:27:06 +03:00
|
|
|
return w.w.Write(buf)
|
|
|
|
}
|
|
|
|
|
2023-12-05 15:35:58 +03:00
|
|
|
func (w *TraceWriter) SetTrace(level slog.Level) {
|
2023-02-03 22:33:19 +03:00
|
|
|
w.level = level
|
|
|
|
}
|
|
|
|
|
|
|
|
type TraceReader struct {
|
2023-12-05 15:35:58 +03:00
|
|
|
log mlog.Log
|
2023-01-30 16:27:06 +03:00
|
|
|
prefix string
|
|
|
|
r io.Reader
|
2023-12-05 15:35:58 +03:00
|
|
|
level slog.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".
|
2023-12-05 15:35:58 +03:00
|
|
|
func NewTraceReader(log mlog.Log, prefix string, r io.Reader) *TraceReader {
|
2023-02-03 22:33:19 +03:00
|
|
|
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.
|
2023-02-03 22:33:19 +03:00
|
|
|
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 {
|
2023-12-05 15:35:58 +03:00
|
|
|
r.log.Trace(r.level, r.prefix, buf[:n])
|
2023-01-30 16:27:06 +03:00
|
|
|
}
|
|
|
|
return n, err
|
|
|
|
}
|
2023-02-03 22:33:19 +03:00
|
|
|
|
2023-12-05 15:35:58 +03:00
|
|
|
func (r *TraceReader) SetTrace(level slog.Level) {
|
2023-02-03 22:33:19 +03:00
|
|
|
r.level = level
|
|
|
|
}
|