log.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. package logging
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "github.com/kptyun/KPTCOMM/pkg/file"
  6. "io"
  7. "log"
  8. "os"
  9. "path/filepath"
  10. "runtime"
  11. "time"
  12. )
  13. type Level int
  14. var (
  15. F *os.File
  16. DefaultPrefix = ""
  17. DefaultCallerDepth = 2
  18. logger *log.Logger
  19. logPrefix = ""
  20. levelFlags = []string{"DEBUG", "INFO", "WARN", "ERROR", "FATAL"}
  21. )
  22. const (
  23. DEBUG Level = iota
  24. INFO
  25. WARNING
  26. ERROR
  27. FATAL
  28. )
  29. func Setup() {
  30. var err error
  31. //tchan :=time.Tick(24*time.Hour)
  32. filePath := getLogFilePath()
  33. fileName := getLogFileName()
  34. F, err = file.MustOpen(fileName, filePath)
  35. if err != nil {
  36. log.Fatalf("logging.Setup err: %v", err)
  37. }
  38. logger = log.New(F, DefaultPrefix, log.LstdFlags)
  39. //gin.DefaultWriter = io.MultiWriter(F, os.Stdout)
  40. go func() {
  41. tchan := time.Tick(24 * time.Hour)
  42. for {
  43. select {
  44. case <-tchan:
  45. F.Close()
  46. fmt.Println("t1定时器")
  47. filePath := getLogFilePath()
  48. fileName := getLogFileName()
  49. F, err = file.MustOpen(fileName, filePath)
  50. if err != nil {
  51. log.Fatalf("logging.Setup err: %v", err)
  52. }
  53. logger = log.New(F, DefaultPrefix, log.LstdFlags)
  54. gin.DefaultWriter = io.MultiWriter(F, os.Stdout)
  55. }
  56. }
  57. }()
  58. //// gin log设置
  59. //gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
  60. //
  61. // // 你的自定义格式
  62. // return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"%s\n",
  63. // param.ClientIP,
  64. // param.TimeStamp.Format(time.RFC1123),
  65. // param.Method,
  66. // param.Path,
  67. // param.Request.Proto,
  68. // param.StatusCode,
  69. // param.Latency,
  70. // param.Request.UserAgent(),
  71. // param.ErrorMessage,
  72. // param.Request.Form,
  73. // )
  74. //})
  75. }
  76. func Debug(v ...interface{}) {
  77. setPrefix(DEBUG)
  78. logger.Println(v)
  79. }
  80. func Info(v ...interface{}) {
  81. setPrefix(INFO)
  82. logger.Println(v)
  83. }
  84. func Warn(v ...interface{}) {
  85. setPrefix(WARNING)
  86. logger.Println(v)
  87. }
  88. func Error(v ...interface{}) {
  89. setPrefix(ERROR)
  90. logger.Println(v)
  91. }
  92. func Fatal(v ...interface{}) {
  93. setPrefix(FATAL)
  94. logger.Fatalln(v)
  95. }
  96. func setPrefix(level Level) {
  97. _, file, line, ok := runtime.Caller(DefaultCallerDepth)
  98. if ok {
  99. logPrefix = fmt.Sprintf("[%s][%s:%d]", levelFlags[level], filepath.Base(file), line)
  100. } else {
  101. logPrefix = fmt.Sprintf("[%s]", levelFlags[level])
  102. }
  103. logger.SetPrefix(logPrefix)
  104. }