tendermint/log/tm_logger.go

84 lines
2.5 KiB
Go
Raw Normal View History

package log
import (
"fmt"
"io"
kitlog "github.com/go-kit/kit/log"
2017-05-05 04:06:56 -07:00
kitlevel "github.com/go-kit/kit/log/level"
"github.com/go-kit/kit/log/term"
)
const (
msgKey = "_msg" // "_" prefixed to avoid collisions
moduleKey = "module"
)
type tmLogger struct {
srcLogger kitlog.Logger
}
2017-05-04 08:39:16 -07:00
// Interface assertions
var _ Logger = (*tmLogger)(nil)
2017-05-02 11:26:00 -07:00
// NewTMTermLogger returns a logger that encodes msg and keyvals to the Writer
// using go-kit's log as an underlying logger and our custom formatter. Note
// that underlying logger could be swapped with something else.
2017-05-02 11:26:00 -07:00
func NewTMLogger(w io.Writer) Logger {
// Color by level value
colorFn := func(keyvals ...interface{}) term.FgBgColor {
2017-05-05 04:06:56 -07:00
if keyvals[0] != kitlevel.Key() {
panic(fmt.Sprintf("expected level key to be first, got %v", keyvals[0]))
}
2017-05-05 04:06:56 -07:00
switch keyvals[1].(kitlevel.Value).String() {
case "debug":
return term.FgBgColor{Fg: term.DarkGray}
case "error":
return term.FgBgColor{Fg: term.Red}
default:
return term.FgBgColor{}
}
}
2017-05-05 04:06:56 -07:00
return &tmLogger{term.NewLogger(w, NewTMFmtLogger, colorFn)}
}
2017-05-23 08:37:13 -07:00
// NewTMLoggerWithColorFn allows you to provide your own color function. See
2017-05-14 03:03:45 -07:00
// NewTMLogger for documentation.
func NewTMLoggerWithColorFn(w io.Writer, colorFn func(keyvals ...interface{}) term.FgBgColor) Logger {
return &tmLogger{term.NewLogger(w, NewTMFmtLogger, colorFn)}
}
// Info logs a message at level Info.
func (l *tmLogger) Info(msg string, keyvals ...interface{}) {
2017-05-05 04:06:56 -07:00
lWithLevel := kitlevel.Info(l.srcLogger)
2017-11-06 11:18:42 -08:00
if err := kitlog.With(lWithLevel, msgKey, msg).Log(keyvals...); err != nil {
errLogger := kitlevel.Error(l.srcLogger)
kitlog.With(errLogger, msgKey, msg).Log("err", err)
}
}
// Debug logs a message at level Debug.
func (l *tmLogger) Debug(msg string, keyvals ...interface{}) {
2017-05-05 04:06:56 -07:00
lWithLevel := kitlevel.Debug(l.srcLogger)
2017-11-06 11:18:42 -08:00
if err := kitlog.With(lWithLevel, msgKey, msg).Log(keyvals...); err != nil {
errLogger := kitlevel.Error(l.srcLogger)
kitlog.With(errLogger, msgKey, msg).Log("err", err)
}
}
// Error logs a message at level Error.
func (l *tmLogger) Error(msg string, keyvals ...interface{}) {
2017-05-05 04:06:56 -07:00
lWithLevel := kitlevel.Error(l.srcLogger)
2017-11-06 11:18:42 -08:00
lWithMsg := kitlog.With(lWithLevel, msgKey, msg)
if err := lWithMsg.Log(keyvals...); err != nil {
lWithMsg.Log("err", err)
}
}
2017-05-04 08:39:16 -07:00
// With returns a new contextual logger with keyvals prepended to those passed
// to calls to Info, Debug or Error.
func (l *tmLogger) With(keyvals ...interface{}) Logger {
return &tmLogger{kitlog.With(l.srcLogger, keyvals...)}
}