log.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. package logging
  2. import (
  3. "fmt"
  4. "io"
  5. "log"
  6. "os"
  7. "path/filepath"
  8. "runtime"
  9. "time"
  10. "tmr-watch/conf/setting"
  11. "tmr-watch/pkg/file"
  12. "github.com/gin-gonic/gin"
  13. )
  14. type Level int
  15. var (
  16. F *os.File
  17. DefaultPrefix = ""
  18. DefaultCallerDepth = 2
  19. DefaultPath string
  20. logger *log.Logger
  21. logPrefix = ""
  22. levelFlags = []string{"DEBUG", "INFO", "WARN", "ERROR", "FATAL"}
  23. )
  24. const (
  25. DEBUG Level = iota
  26. INFO
  27. WARNING
  28. ERROR
  29. FATAL
  30. )
  31. func Setup() {
  32. var err error
  33. filePath := fmt.Sprintf("./%s", getLogFilePath(setting.AppSetting.RuntimeRootPath, setting.AppSetting.LogSavePath))
  34. fileName := getLogFileName(setting.AppSetting.LogSaveName, setting.AppSetting.TimeFormat, setting.AppSetting.LogFileExt)
  35. F, err = file.MustOpen(fileName, filePath)
  36. if err != nil {
  37. log.Fatalf("logging.Setup err: %v", err)
  38. }
  39. logger = log.New(F, DefaultPrefix, log.LstdFlags)
  40. gin.DefaultWriter = io.MultiWriter(F, logger.Writer())
  41. go func() {
  42. defer func() {
  43. if err := recover(); err != nil {
  44. log.Fatalf("logging.recover err: %v", err)
  45. }
  46. }()
  47. tchan := time.Tick(24 * time.Hour)
  48. for {
  49. select {
  50. case <-tchan:
  51. F.Close()
  52. F, err = file.MustOpen(fileName, filePath)
  53. if err != nil {
  54. log.Fatalf("logging.Setup err: %v", err)
  55. }
  56. logger = log.New(F, DefaultPrefix, log.LstdFlags)
  57. gin.DefaultWriter = io.MultiWriter(F, logger.Writer())
  58. }
  59. }
  60. }()
  61. }
  62. func Printf(format string, v ...interface{}) {
  63. setPrefix(INFO)
  64. logger.Printf(format, v)
  65. }
  66. func Println(v ...interface{}) {
  67. setPrefix(INFO)
  68. logger.Println(v)
  69. }
  70. func Debug(v ...interface{}) {
  71. setPrefix(DEBUG)
  72. logger.Println(v)
  73. }
  74. func Info(v ...interface{}) {
  75. setPrefix(INFO)
  76. logger.Println(v)
  77. }
  78. func Warn(v ...interface{}) {
  79. setPrefix(WARNING)
  80. logger.Println(v)
  81. }
  82. func Error(v ...interface{}) {
  83. setPrefix(ERROR)
  84. logger.Println(v)
  85. }
  86. func Fatal(v ...interface{}) {
  87. setPrefix(FATAL)
  88. logger.Fatalln(v)
  89. }
  90. func setPrefix(level Level) {
  91. _, file, line, ok := runtime.Caller(DefaultCallerDepth)
  92. if ok {
  93. logPrefix = fmt.Sprintf("[%s][%s:%d]", levelFlags[level], filepath.Base(file), line)
  94. } else {
  95. logPrefix = fmt.Sprintf("[%s]", levelFlags[level])
  96. }
  97. logger.SetPrefix(logPrefix)
  98. }