1
0
mirror of https://github.com/go-kratos/kratos.git synced 2025-01-22 03:38:41 +02:00
kratos/log/std.go

48 lines
825 B
Go
Raw Normal View History

2021-02-17 17:14:47 +08:00
package log
import (
"bytes"
"fmt"
"io"
2021-02-17 17:14:47 +08:00
"log"
"sync"
)
var _ Logger = (*stdLogger)(nil)
type stdLogger struct {
log *log.Logger
pool *sync.Pool
}
// NewStdLogger new a logger with writer.
func NewStdLogger(w io.Writer) Logger {
2021-02-17 17:14:47 +08:00
return &stdLogger{
log: log.New(w, "", 0),
2021-02-17 17:14:47 +08:00
pool: &sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
},
}
}
// Log print the kv pairs log.
func (l *stdLogger) Log(level Level, keyvals ...interface{}) error {
if len(keyvals) == 0 {
return nil
2021-02-17 17:14:47 +08:00
}
if len(keyvals)%2 != 0 {
keyvals = append(keyvals, "")
2021-02-17 17:14:47 +08:00
}
buf := l.pool.Get().(*bytes.Buffer)
buf.WriteString(level.String())
for i := 0; i < len(keyvals); i += 2 {
fmt.Fprintf(buf, " %s=%v", keyvals[i], keyvals[i+1])
2021-02-17 17:14:47 +08:00
}
l.log.Output(4, buf.String())
2021-02-17 17:14:47 +08:00
buf.Reset()
l.pool.Put(buf)
return nil
2021-02-17 17:14:47 +08:00
}