logger.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package viper
  2. import (
  3. "fmt"
  4. jww "github.com/spf13/jwalterweatherman"
  5. )
  6. // Logger is a unified interface for various logging use cases and practices, including:
  7. // - leveled logging
  8. // - structured logging
  9. type Logger interface {
  10. // Trace logs a Trace event.
  11. //
  12. // Even more fine-grained information than Debug events.
  13. // Loggers not supporting this level should fall back to Debug.
  14. Trace(msg string, keyvals ...interface{})
  15. // Debug logs a Debug event.
  16. //
  17. // A verbose series of information events.
  18. // They are useful when debugging the system.
  19. Debug(msg string, keyvals ...interface{})
  20. // Info logs an Info event.
  21. //
  22. // General information about what's happening inside the system.
  23. Info(msg string, keyvals ...interface{})
  24. // Warn logs a Warn(ing) event.
  25. //
  26. // Non-critical events that should be looked at.
  27. Warn(msg string, keyvals ...interface{})
  28. // Error logs an Error event.
  29. //
  30. // Critical events that require immediate attention.
  31. // Loggers commonly provide Fatal and Panic levels above Error level,
  32. // but exiting and panicing is out of scope for a logging library.
  33. Error(msg string, keyvals ...interface{})
  34. }
  35. type jwwLogger struct{}
  36. func (jwwLogger) Trace(msg string, keyvals ...interface{}) {
  37. jww.TRACE.Printf(jwwLogMessage(msg, keyvals...))
  38. }
  39. func (jwwLogger) Debug(msg string, keyvals ...interface{}) {
  40. jww.DEBUG.Printf(jwwLogMessage(msg, keyvals...))
  41. }
  42. func (jwwLogger) Info(msg string, keyvals ...interface{}) {
  43. jww.INFO.Printf(jwwLogMessage(msg, keyvals...))
  44. }
  45. func (jwwLogger) Warn(msg string, keyvals ...interface{}) {
  46. jww.WARN.Printf(jwwLogMessage(msg, keyvals...))
  47. }
  48. func (jwwLogger) Error(msg string, keyvals ...interface{}) {
  49. jww.ERROR.Printf(jwwLogMessage(msg, keyvals...))
  50. }
  51. func jwwLogMessage(msg string, keyvals ...interface{}) string {
  52. out := msg
  53. if len(keyvals) > 0 && len(keyvals)%2 == 1 {
  54. keyvals = append(keyvals, nil)
  55. }
  56. for i := 0; i <= len(keyvals)-2; i += 2 {
  57. out = fmt.Sprintf("%s %v=%v", out, keyvals[i], keyvals[i+1])
  58. }
  59. return out
  60. }