1package moxio
2
3import (
4 "io"
5 "log/slog"
6
7 "github.com/mjl-/mox/mlog"
8)
9
10type TraceWriter struct {
11 log mlog.Log
12 prefix string
13 w io.Writer
14 level slog.Level
15}
16
17// NewTraceWriter wraps "w" into a writer that logs all writes to "log" with
18// log level trace, prefixed with "prefix".
19func NewTraceWriter(log mlog.Log, prefix string, w io.Writer) *TraceWriter {
20 return &TraceWriter{log, prefix, w, mlog.LevelTrace}
21}
22
23// Write logs a trace line for writing buf to the client, then writes to the
24// client.
25func (w *TraceWriter) Write(buf []byte) (int, error) {
26 w.log.Trace(w.level, w.prefix, buf)
27 return w.w.Write(buf)
28}
29
30func (w *TraceWriter) SetTrace(level slog.Level) {
31 w.level = level
32}
33
34type TraceReader struct {
35 log mlog.Log
36 prefix string
37 r io.Reader
38 level slog.Level
39}
40
41// NewTraceReader wraps reader "r" into a reader that logs all reads to "log"
42// with log level trace, prefixed with "prefix".
43func NewTraceReader(log mlog.Log, prefix string, r io.Reader) *TraceReader {
44 return &TraceReader{log, prefix, r, mlog.LevelTrace}
45}
46
47// Read does a single Read on its underlying reader, logs data of successful
48// reads, and returns the data read.
49func (r *TraceReader) Read(buf []byte) (int, error) {
50 n, err := r.r.Read(buf)
51 if n > 0 {
52 r.log.Trace(r.level, r.prefix, buf[:n])
53 }
54 return n, err
55}
56
57func (r *TraceReader) SetTrace(level slog.Level) {
58 r.level = level
59}
60