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.1 KiB

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. "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. // NewTMTermLogger returns a logger that encodes msg and keyvals to the Writer
  16. // using go-kit's log as an underlying logger and our custom formatter. Note
  17. // that underlying logger could be swapped with something else.
  18. func NewTMLogger(w io.Writer) Logger {
  19. // Color by level value
  20. colorFn := func(keyvals ...interface{}) term.FgBgColor {
  21. if keyvals[0] != level.Key() {
  22. panic(fmt.Sprintf("expected level key to be first, got %v", keyvals[0]))
  23. }
  24. switch keyvals[1].(level.Value).String() {
  25. case "debug":
  26. return term.FgBgColor{Fg: term.DarkGray}
  27. case "error":
  28. return term.FgBgColor{Fg: term.Red}
  29. default:
  30. return term.FgBgColor{}
  31. }
  32. }
  33. srcLogger := term.NewLogger(w, NewTMFmtLogger, colorFn)
  34. srcLogger = level.NewFilter(srcLogger, level.AllowInfo())
  35. return &tmLogger{srcLogger}
  36. }
  37. // WithLevel returns a copy of the logger with a level set to lvl.
  38. func (l *tmLogger) WithLevel(lvl string) Logger {
  39. switch lvl {
  40. case "info":
  41. return &tmLogger{level.NewFilter(l.srcLogger, level.AllowInfo())}
  42. case "debug":
  43. return &tmLogger{level.NewFilter(l.srcLogger, level.AllowDebug())}
  44. case "error":
  45. return &tmLogger{level.NewFilter(l.srcLogger, level.AllowError())}
  46. default:
  47. panic(fmt.Sprintf("Unexpected level %v, expect either \"info\" or \"debug\" or \"error\"", lvl))
  48. }
  49. }
  50. // Info logs a message at level Info.
  51. func (l *tmLogger) Info(msg string, keyvals ...interface{}) error {
  52. lWithLevel := level.Info(l.srcLogger)
  53. return kitlog.With(lWithLevel, msgKey, msg).Log(keyvals...)
  54. }
  55. // Debug logs a message at level Debug.
  56. func (l *tmLogger) Debug(msg string, keyvals ...interface{}) error {
  57. lWithLevel := level.Debug(l.srcLogger)
  58. return kitlog.With(lWithLevel, msgKey, msg).Log(keyvals...)
  59. }
  60. // Error logs a message at level Error.
  61. func (l *tmLogger) Error(msg string, keyvals ...interface{}) error {
  62. lWithLevel := level.Error(l.srcLogger)
  63. return kitlog.With(lWithLevel, msgKey, msg).Log(keyvals...)
  64. }