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.

36 lines
1.0 KiB

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