codekingpro/portable-devtools
114k
1// Copyright 2009 The Go Authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.4 5package iotest6 7import (8 "io"9 "log"10)11 12type writeLogger struct {13 prefix string14 w io.Writer15}16 17func (l *writeLogger) Write(p []byte) (n int, err error) {18 n, err = l.w.Write(p)19 if err != nil {20 log.Printf("%s %x: %v", l.prefix, p[0:n], err)21 } else {22 log.Printf("%s %x", l.prefix, p[0:n])23 }24 return25}26 27// NewWriteLogger returns a writer that behaves like w except28// that it logs (using [log.Printf]) each write to standard error,29// printing the prefix and the hexadecimal data written.30func NewWriteLogger(prefix string, w io.Writer) io.Writer {31 return &writeLogger{prefix, w}32}33 34type readLogger struct {35 prefix string36 r io.Reader37}38 39func (l *readLogger) Read(p []byte) (n int, err error) {40 n, err = l.r.Read(p)41 if err != nil {42 log.Printf("%s %x: %v", l.prefix, p[0:n], err)43 } else {44 log.Printf("%s %x", l.prefix, p[0:n])45 }46 return47}48 49// NewReadLogger returns a reader that behaves like r except50// that it logs (using [log.Printf]) each read to standard error,51// printing the prefix and the hexadecimal data read.52func NewReadLogger(prefix string, r io.Reader) io.Reader {53 return &readLogger{prefix, r}54}55 