github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/xlog/log.go (about)

     1  package xlog
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  )
     7  
     8  // Logger is abstraction of log behavior.
     9  type Logger interface {
    10  	Print(args ...interface{})
    11  	Printf(format string, args ...interface{})
    12  }
    13  
    14  type writerLogger struct {
    15  	w io.Writer
    16  }
    17  
    18  func (w *writerLogger) Print(args ...interface{}) {
    19  	_, _ = w.w.Write([]byte(fmt.Sprint(args...)))
    20  }
    21  
    22  func (w *writerLogger) Printf(format string, args ...interface{}) {
    23  	_, _ = w.w.Write([]byte(fmt.Sprintf(format, args...)))
    24  }
    25  
    26  // Writer return a Logger which wrap an io.Writer.
    27  func Writer(w io.Writer) Logger {
    28  	return &writerLogger{w: w}
    29  }
    30  
    31  // MultiWriter return a Logger which write data to multiply io.Writer.
    32  func MultiWriter(ws ...io.Writer) Logger {
    33  	if len(ws) == 0 {
    34  		return Nop()
    35  	} else if len(ws) == 1 {
    36  		return Writer(ws[0])
    37  	}
    38  	return &writerLogger{w: io.MultiWriter(ws...)}
    39  }
    40  
    41  type nopLogger struct{}
    42  
    43  func (nopLogger) Print(args ...interface{})                 {}
    44  func (nopLogger) Printf(format string, args ...interface{}) {}
    45  
    46  // Nop return a Logger which do nothing.
    47  func Nop() Logger { return nopLogger{} }