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.

74 lines
2.2 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. // NewTMLoggerWithColorFn allows you to provide your own color function. See
  39. // NewTMLogger for documentation.
  40. func NewTMLoggerWithColorFn(w io.Writer, colorFn func(keyvals ...interface{}) term.FgBgColor) Logger {
  41. return &tmLogger{term.NewLogger(w, NewTMFmtLogger, colorFn)}
  42. }
  43. // Info logs a message at level Info.
  44. func (l *tmLogger) Info(msg string, keyvals ...interface{}) error {
  45. lWithLevel := kitlevel.Info(l.srcLogger)
  46. return kitlog.With(lWithLevel, msgKey, msg).Log(keyvals...)
  47. }
  48. // Debug logs a message at level Debug.
  49. func (l *tmLogger) Debug(msg string, keyvals ...interface{}) error {
  50. lWithLevel := kitlevel.Debug(l.srcLogger)
  51. return kitlog.With(lWithLevel, msgKey, msg).Log(keyvals...)
  52. }
  53. // Error logs a message at level Error.
  54. func (l *tmLogger) Error(msg string, keyvals ...interface{}) error {
  55. lWithLevel := kitlevel.Error(l.srcLogger)
  56. return kitlog.With(lWithLevel, msgKey, msg).Log(keyvals...)
  57. }
  58. // With returns a new contextual logger with keyvals prepended to those passed
  59. // to calls to Info, Debug or Error.
  60. func (l *tmLogger) With(keyvals ...interface{}) Logger {
  61. return &tmLogger{kitlog.With(l.srcLogger, keyvals...)}
  62. }