mirror of
https://github.com/mjl-/mox.git
synced 2024-12-26 16:33:47 +03:00
5b20cba50a
we don't want external software to include internal details like mlog. slog.Logger is/will be the standard. we still have mlog for its helper functions, and its handler that logs in concise logfmt used by mox. packages that are not meant for reuse still pass around mlog.Log for convenience. we use golang.org/x/exp/slog because we also support the previous Go toolchain version. with the next Go release, we'll switch to the builtin slog.
60 lines
1.4 KiB
Go
60 lines
1.4 KiB
Go
package moxio
|
|
|
|
import (
|
|
"io"
|
|
|
|
"golang.org/x/exp/slog"
|
|
|
|
"github.com/mjl-/mox/mlog"
|
|
)
|
|
|
|
type TraceWriter struct {
|
|
log mlog.Log
|
|
prefix string
|
|
w io.Writer
|
|
level slog.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, buf)
|
|
return w.w.Write(buf)
|
|
}
|
|
|
|
func (w *TraceWriter) SetTrace(level slog.Level) {
|
|
w.level = level
|
|
}
|
|
|
|
type TraceReader struct {
|
|
log mlog.Log
|
|
prefix string
|
|
r io.Reader
|
|
level slog.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, buf[:n])
|
|
}
|
|
return n, err
|
|
}
|
|
|
|
func (r *TraceReader) SetTrace(level slog.Level) {
|
|
r.level = level
|
|
}
|