github.com/songzhibin97/gkit@v1.2.13/log/std.go (about)

     1  package log
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"io"
     7  	"log"
     8  	"sync"
     9  )
    10  
    11  var _ Logger = (*stdLogger)(nil)
    12  
    13  type stdLogger struct {
    14  	log  *log.Logger
    15  	pool *sync.Pool
    16  }
    17  
    18  // NewStdLogger new a logger with writer.
    19  func NewStdLogger(w io.Writer) Logger {
    20  	return &stdLogger{
    21  		log: log.New(w, "", 0),
    22  		pool: &sync.Pool{
    23  			New: func() interface{} {
    24  				return new(bytes.Buffer)
    25  			},
    26  		},
    27  	}
    28  }
    29  
    30  // Log print the kv pairs log.
    31  func (l *stdLogger) Log(level Lever, kvs ...interface{}) error {
    32  	if len(kvs) == 0 {
    33  		return nil
    34  	}
    35  	if len(kvs)%2 != 0 {
    36  		kvs = append(kvs, "")
    37  	}
    38  	buf := l.pool.Get().(*bytes.Buffer)
    39  	buf.WriteString(level.String())
    40  	for i := 0; i < len(kvs); i += 2 {
    41  		fmt.Fprintf(buf, " %s=%v", kvs[i], kvs[i+1])
    42  	}
    43  	l.log.Output(4, buf.String())
    44  	buf.Reset()
    45  	l.pool.Put(buf)
    46  	return nil
    47  }