log.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package go_chat_api_util
  2. import (
  3. "github.com/lestrrat-go/file-rotatelogs"
  4. "github.com/sirupsen/logrus"
  5. "io"
  6. "time"
  7. )
  8. var log *logrus.Logger
  9. type RotateConfig struct {
  10. MaxAge time.Duration //最大时间
  11. RotationTime time.Duration //分隔间隔
  12. }
  13. type RotateOption func(config *RotateConfig)
  14. func WithMaxAge(age time.Duration) RotateOption {
  15. return func(q *RotateConfig) {
  16. q.MaxAge = age
  17. }
  18. }
  19. func WithRotationTime(roTime time.Duration) RotateOption {
  20. return func(config *RotateConfig) {
  21. config.RotationTime = roTime
  22. }
  23. }
  24. func NewLoggerByLogName(path string, options ...RotateOption) (*logrus.Logger, error) {
  25. co := &RotateConfig{MaxAge: 24 * 31 * 12 * time.Hour * 2, RotationTime: 7 * 24 * time.Hour}
  26. for _, v := range options {
  27. v(co)
  28. }
  29. writer, err := rotatelogs.New(
  30. path+".%Y%m%d%H%M",
  31. rotatelogs.WithLinkName(path),
  32. rotatelogs.WithMaxAge(co.MaxAge),
  33. rotatelogs.WithRotationTime(co.RotationTime),
  34. )
  35. if err != nil {
  36. return nil, err
  37. }
  38. return NewLogger(writer), err
  39. }
  40. func NewLogger(f io.Writer) *logrus.Logger {
  41. log = logrus.New()
  42. log.Formatter = &logrus.JSONFormatter{}
  43. //f, err := os.OpenFile("./log/log.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
  44. //if err != nil {
  45. // panic("不能打开日志文件 " + err.Error())
  46. //}
  47. customF := new(logrus.JSONFormatter)
  48. customF.TimestampFormat = "2006-01-02 15:04:05"
  49. log.SetFormatter(customF)
  50. log.SetLevel(logrus.DebugLevel)
  51. //log.Out = f
  52. log.Out = f
  53. return log
  54. }