lg.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // short for "log"
  2. package lg
  3. import (
  4. "fmt"
  5. "log"
  6. "os"
  7. "strings"
  8. )
  9. const (
  10. DEBUG = LogLevel(1)
  11. INFO = LogLevel(2)
  12. WARN = LogLevel(3)
  13. ERROR = LogLevel(4)
  14. FATAL = LogLevel(5)
  15. )
  16. type AppLogFunc func(lvl LogLevel, f string, args ...interface{})
  17. type Logger interface {
  18. Output(maxdepth int, s string) error
  19. }
  20. type NilLogger struct{}
  21. func (l NilLogger) Output(maxdepth int, s string) error {
  22. return nil
  23. }
  24. type LogLevel int
  25. func (l *LogLevel) Get() interface{} { return *l }
  26. func (l *LogLevel) Set(s string) error {
  27. lvl, err := ParseLogLevel(s)
  28. if err != nil {
  29. return err
  30. }
  31. *l = lvl
  32. return nil
  33. }
  34. func (l *LogLevel) String() string {
  35. switch *l {
  36. case DEBUG:
  37. return "DEBUG"
  38. case INFO:
  39. return "INFO"
  40. case WARN:
  41. return "WARNING"
  42. case ERROR:
  43. return "ERROR"
  44. case FATAL:
  45. return "FATAL"
  46. }
  47. return "invalid"
  48. }
  49. func ParseLogLevel(levelstr string) (LogLevel, error) {
  50. switch strings.ToLower(levelstr) {
  51. case "debug":
  52. return DEBUG, nil
  53. case "info":
  54. return INFO, nil
  55. case "warn":
  56. return WARN, nil
  57. case "error":
  58. return ERROR, nil
  59. case "fatal":
  60. return FATAL, nil
  61. }
  62. return 0, fmt.Errorf("invalid log level '%s' (debug, info, warn, error, fatal)", levelstr)
  63. }
  64. func Logf(logger Logger, cfgLevel LogLevel, msgLevel LogLevel, f string, args ...interface{}) {
  65. if cfgLevel > msgLevel {
  66. return
  67. }
  68. logger.Output(3, fmt.Sprintf(msgLevel.String()+": "+f, args...))
  69. }
  70. func LogFatal(prefix string, f string, args ...interface{}) {
  71. logger := log.New(os.Stderr, prefix, log.Ldate|log.Ltime|log.Lmicroseconds)
  72. Logf(logger, FATAL, FATAL, f, args...)
  73. os.Exit(1)
  74. }