You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
1.2 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. package qmlog
  2. // 日志初始化包 调用qmlog.QMLog.Info 记录日志 24小时切割 日志保存7天 可自行设置
  3. import (
  4. "fmt"
  5. "gin-vue-admin/tools"
  6. rotatelogs "github.com/lestrrat/go-file-rotatelogs"
  7. "github.com/rifflock/lfshook"
  8. "github.com/sirupsen/logrus"
  9. "os"
  10. "time"
  11. )
  12. var QMLog = logrus.New()
  13. //禁止logrus的输出
  14. func InitLog() *logrus.Logger {
  15. src, err := os.OpenFile(os.DevNull, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
  16. if err != nil {
  17. fmt.Println("err", err)
  18. }
  19. QMLog.Out = src
  20. QMLog.SetLevel(logrus.DebugLevel)
  21. if ok, _ := tools.PathExists("./log"); !ok {
  22. // Directory not exist
  23. fmt.Println("Create log.")
  24. _ = os.Mkdir("log", os.ModePerm)
  25. }
  26. apiLogPath := "./log/api.log"
  27. logWriter, err := rotatelogs.New(
  28. apiLogPath+".%Y-%m-%d-%H-%M.log",
  29. rotatelogs.WithLinkName(apiLogPath), // 生成软链,指向最新日志文件
  30. rotatelogs.WithMaxAge(7*24*time.Hour), // 文件最大保存时间
  31. rotatelogs.WithRotationTime(24*time.Hour), // 日志切割时间间隔
  32. )
  33. writeMap := lfshook.WriterMap{
  34. logrus.InfoLevel: logWriter,
  35. logrus.FatalLevel: logWriter,
  36. }
  37. lfHook := lfshook.NewHook(writeMap, &logrus.JSONFormatter{})
  38. QMLog.AddHook(lfHook)
  39. return QMLog
  40. }