oss.indeed.com/go/go-opine@v1.3.0/internal/printing/log_writer.go (about)

     1  package printing
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"sync"
     7  )
     8  
     9  func NewLogWriter(to io.Writer) *LogWriter {
    10  	return &LogWriter{out: to}
    11  }
    12  
    13  // LogWriter wraps an io.Writer and ignores errors when writing. It also
    14  // provides a Logf method similar to log.Printf.
    15  type LogWriter struct {
    16  	out io.Writer
    17  	mu  sync.Mutex
    18  }
    19  
    20  var _ io.Writer = (*LogWriter)(nil)
    21  
    22  // Write to the underlying io.Writer. Errors are silently ignored. Always
    23  // returns len(p) and a nil error.
    24  func (lw *LogWriter) Write(p []byte) (n int, err error) {
    25  	lw.mu.Lock()
    26  	defer lw.mu.Unlock()
    27  	_, _ = lw.out.Write(p)
    28  	return len(p), nil
    29  }
    30  
    31  // Logf will write a log line to the underlying io.Writer. A newline is
    32  // automatically appended.
    33  func (lw *LogWriter) Logf(format string, a ...interface{}) {
    34  	_, _ = fmt.Fprintf(lw, format+"\n", a...)
    35  }