github.com/supragya/TendermintConnector@v0.0.0-20210619045051-113e32b84fb1/chains/tm34/libs/log/tm_logger.go (about) 1 package log 2 3 import ( 4 "fmt" 5 "io" 6 7 kitlog "github.com/go-kit/kit/log" 8 kitlevel "github.com/go-kit/kit/log/level" 9 "github.com/go-kit/kit/log/term" 10 ) 11 12 const ( 13 msgKey = "_msg" // "_" prefixed to avoid collisions 14 moduleKey = "module" 15 ) 16 17 type tmLogger struct { 18 srcLogger kitlog.Logger 19 } 20 21 // Interface assertions 22 var _ Logger = (*tmLogger)(nil) 23 24 // NewTMLogger returns a logger that encodes msg and keyvals to the Writer 25 // using go-kit's log as an underlying logger and our custom formatter. Note 26 // that underlying logger could be swapped with something else. 27 func NewTMLogger(w io.Writer) Logger { 28 // Color by level value 29 colorFn := func(keyvals ...interface{}) term.FgBgColor { 30 if keyvals[0] != kitlevel.Key() { 31 panic(fmt.Sprintf("expected level key to be first, got %v", keyvals[0])) 32 } 33 switch keyvals[1].(kitlevel.Value).String() { 34 case "debug": 35 return term.FgBgColor{Fg: term.DarkGray} 36 case "error": 37 return term.FgBgColor{Fg: term.Red} 38 default: 39 return term.FgBgColor{} 40 } 41 } 42 43 return &tmLogger{term.NewLogger(w, NewTMFmtLogger, colorFn)} 44 } 45 46 // NewTMLoggerWithColorFn allows you to provide your own color function. See 47 // NewTMLogger for documentation. 48 func NewTMLoggerWithColorFn(w io.Writer, colorFn func(keyvals ...interface{}) term.FgBgColor) Logger { 49 return &tmLogger{term.NewLogger(w, NewTMFmtLogger, colorFn)} 50 } 51 52 // Info logs a message at level Info. 53 func (l *tmLogger) Info(msg string, keyvals ...interface{}) { 54 lWithLevel := kitlevel.Info(l.srcLogger) 55 56 if err := kitlog.With(lWithLevel, msgKey, msg).Log(keyvals...); err != nil { 57 errLogger := kitlevel.Error(l.srcLogger) 58 kitlog.With(errLogger, msgKey, msg).Log("err", err) //nolint:errcheck // no need to check error again 59 } 60 } 61 62 // Debug logs a message at level Debug. 63 func (l *tmLogger) Debug(msg string, keyvals ...interface{}) { 64 lWithLevel := kitlevel.Debug(l.srcLogger) 65 66 if err := kitlog.With(lWithLevel, msgKey, msg).Log(keyvals...); err != nil { 67 errLogger := kitlevel.Error(l.srcLogger) 68 kitlog.With(errLogger, msgKey, msg).Log("err", err) //nolint:errcheck // no need to check error again 69 } 70 } 71 72 // Error logs a message at level Error. 73 func (l *tmLogger) Error(msg string, keyvals ...interface{}) { 74 lWithLevel := kitlevel.Error(l.srcLogger) 75 76 lWithMsg := kitlog.With(lWithLevel, msgKey, msg) 77 if err := lWithMsg.Log(keyvals...); err != nil { 78 lWithMsg.Log("err", err) //nolint:errcheck // no need to check error again 79 } 80 } 81 82 // With returns a new contextual logger with keyvals prepended to those passed 83 // to calls to Info, Debug or Error. 84 func (l *tmLogger) With(keyvals ...interface{}) Logger { 85 return &tmLogger{kitlog.With(l.srcLogger, keyvals...)} 86 }