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.

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