logger.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. package myth
  2. import (
  3. "io"
  4. "log"
  5. "os"
  6. )
  7. // Logger logger
  8. type Logger struct {
  9. logger *log.Logger
  10. }
  11. var (
  12. defLog *Logger
  13. defFP *os.File
  14. )
  15. // NewDefaultLogger defult logger
  16. func NewDefaultLogger(path string) (*Logger, error) {
  17. var err error
  18. fp := &os.File{}
  19. if fp, err = os.OpenFile(path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666); err != nil {
  20. return nil, err
  21. }
  22. defLog = NewLogger(fp)
  23. defFP = fp
  24. return defLog, nil
  25. }
  26. // ReopenDefaultLogger re open default logger
  27. func ReopenDefaultLogger(path string) (*Logger, error) {
  28. var err error
  29. fp := &os.File{}
  30. if fp, err = os.OpenFile(path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666); err != nil {
  31. return nil, err
  32. }
  33. if defLog == nil {
  34. defLog = NewLogger(fp)
  35. }
  36. return defLog, nil
  37. }
  38. // CloseDefaultLogger close
  39. func CloseDefaultLogger() error {
  40. return defFP.Close()
  41. }
  42. // LogDebug debug
  43. func LogDebug(v ...interface{}) {
  44. defLog.logger.SetPrefix("[DEBUG]")
  45. defLog.logger.Println(v...)
  46. }
  47. // LogInfo info
  48. func LogInfo(v ...interface{}) {
  49. defLog.logger.SetPrefix("[INFO]")
  50. defLog.logger.Println(v...)
  51. }
  52. // LogWarn warn
  53. func LogWarn(v ...interface{}) {
  54. defLog.logger.SetPrefix("[Warn]")
  55. defLog.logger.Println(v...)
  56. }
  57. // LogErr err
  58. func LogErr(v ...interface{}) {
  59. defLog.logger.SetPrefix("[Err]")
  60. defLog.logger.Println(v...)
  61. }
  62. // LogAlert alert
  63. func LogAlert(v ...interface{}) {
  64. defLog.logger.SetPrefix("[Alert]")
  65. defLog.logger.Println(v...)
  66. }
  67. // NewLogger new logger
  68. func NewLogger(out io.Writer) *Logger {
  69. logger := log.New(out, "[INFO]", log.Ldate|log.Ltime)
  70. return &Logger{logger: logger}
  71. }
  72. // Info log info
  73. func (l *Logger) Info(v ...interface{}) {
  74. l.logger.SetPrefix("[INFO]")
  75. l.logger.Println(v...)
  76. }
  77. // Debug log debug
  78. func (l *Logger) Debug(v ...interface{}) {
  79. l.logger.SetPrefix("[DEBUG]")
  80. l.logger.Println(v...)
  81. }
  82. // Warn log Warn
  83. func (l *Logger) Warn(v ...interface{}) {
  84. l.logger.SetPrefix("[Warn]")
  85. l.logger.Println(v...)
  86. }
  87. // Err log Err
  88. func (l *Logger) Err(v ...interface{}) {
  89. l.logger.SetPrefix("[Err]")
  90. l.logger.Println(v...)
  91. }
  92. // Alert log Alert
  93. func (l *Logger) Alert(v ...interface{}) {
  94. l.logger.SetPrefix("[Alert]")
  95. l.logger.Println(v...)
  96. }