You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.9 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. package log
  2. import (
  3. "fmt"
  4. "io"
  5. kitlog "github.com/go-kit/kit/log"
  6. kitlevel "github.com/go-kit/kit/log/level"
  7. "github.com/go-kit/kit/log/term"
  8. )
  9. const (
  10. msgKey = "_msg" // "_" prefixed to avoid collisions
  11. )
  12. type tmLogger struct {
  13. srcLogger kitlog.Logger
  14. }
  15. // Interface assertions
  16. var _ Logger = (*tmLogger)(nil)
  17. // NewTMTermLogger returns a logger that encodes msg and keyvals to the Writer
  18. // using go-kit's log as an underlying logger and our custom formatter. Note
  19. // that underlying logger could be swapped with something else.
  20. func NewTMLogger(w io.Writer) Logger {
  21. // Color by level value
  22. colorFn := func(keyvals ...interface{}) term.FgBgColor {
  23. if keyvals[0] != kitlevel.Key() {
  24. panic(fmt.Sprintf("expected level key to be first, got %v", keyvals[0]))
  25. }
  26. switch keyvals[1].(kitlevel.Value).String() {
  27. case "debug":
  28. return term.FgBgColor{Fg: term.DarkGray}
  29. case "error":
  30. return term.FgBgColor{Fg: term.Red}
  31. default:
  32. return term.FgBgColor{}
  33. }
  34. }
  35. return &tmLogger{term.NewLogger(w, NewTMFmtLogger, colorFn)}
  36. }
  37. // Info logs a message at level Info.
  38. func (l *tmLogger) Info(msg string, keyvals ...interface{}) error {
  39. lWithLevel := kitlevel.Info(l.srcLogger)
  40. return kitlog.With(lWithLevel, msgKey, msg).Log(keyvals...)
  41. }
  42. // Debug logs a message at level Debug.
  43. func (l *tmLogger) Debug(msg string, keyvals ...interface{}) error {
  44. lWithLevel := kitlevel.Debug(l.srcLogger)
  45. return kitlog.With(lWithLevel, msgKey, msg).Log(keyvals...)
  46. }
  47. // Error logs a message at level Error.
  48. func (l *tmLogger) Error(msg string, keyvals ...interface{}) error {
  49. lWithLevel := kitlevel.Error(l.srcLogger)
  50. return kitlog.With(lWithLevel, msgKey, msg).Log(keyvals...)
  51. }
  52. // With returns a new contextual logger with keyvals prepended to those passed
  53. // to calls to Info, Debug or Error.
  54. func (l *tmLogger) With(keyvals ...interface{}) Logger {
  55. return &tmLogger{kitlog.With(l.srcLogger, keyvals...)}
  56. }