log.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package log
  2. import (
  3. "log"
  4. "strings"
  5. "sync"
  6. )
  7. // Level is a well-known log level, as defined below
  8. type Level int
  9. // Well known log levels
  10. const (
  11. DebugLevel Level = iota
  12. InfoLevel
  13. WarnLevel
  14. ErrorLevel
  15. )
  16. func (l Level) String() string {
  17. switch l {
  18. case DebugLevel:
  19. return "DEBUG"
  20. case InfoLevel:
  21. return "INFO"
  22. case WarnLevel:
  23. return "WARN"
  24. case ErrorLevel:
  25. return "ERROR"
  26. }
  27. return "unknown"
  28. }
  29. var (
  30. level = InfoLevel
  31. mu = &sync.Mutex{}
  32. )
  33. // Debug prints the given message, if the current log level is DEBUG
  34. func Debug(message string, v ...interface{}) {
  35. logIf(DebugLevel, message, v...)
  36. }
  37. // Info prints the given message, if the current log level is INFO or lower
  38. func Info(message string, v ...interface{}) {
  39. logIf(InfoLevel, message, v...)
  40. }
  41. // Warn prints the given message, if the current log level is WARN or lower
  42. func Warn(message string, v ...interface{}) {
  43. logIf(WarnLevel, message, v...)
  44. }
  45. // Error prints the given message, if the current log level is ERROR or lower
  46. func Error(message string, v ...interface{}) {
  47. logIf(ErrorLevel, message, v...)
  48. }
  49. // Fatal prints the given message, and exits the program
  50. func Fatal(v ...interface{}) {
  51. log.Fatalln(v...)
  52. }
  53. // CurrentLevel returns the current log level
  54. func CurrentLevel() Level {
  55. mu.Lock()
  56. defer mu.Unlock()
  57. return level
  58. }
  59. // SetLevel sets a new log level
  60. func SetLevel(newLevel Level) {
  61. mu.Lock()
  62. defer mu.Unlock()
  63. level = newLevel
  64. }
  65. // ToLevel converts a string to a Level. It returns InfoLevel if the string
  66. // does not match any known log levels.
  67. func ToLevel(s string) Level {
  68. switch strings.ToLower(s) {
  69. case "debug":
  70. return DebugLevel
  71. case "info":
  72. return InfoLevel
  73. case "warn", "warning":
  74. return WarnLevel
  75. case "error":
  76. return ErrorLevel
  77. default:
  78. return InfoLevel
  79. }
  80. }
  81. func logIf(l Level, message string, v ...interface{}) {
  82. if CurrentLevel() <= l {
  83. log.Printf(l.String()+" "+message, v...)
  84. }
  85. }