log.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package go_chat_api_util
  2. import (
  3. "github.com/lestrrat-go/file-rotatelogs"
  4. "github.com/sirupsen/logrus"
  5. "io"
  6. "runtime"
  7. "strconv"
  8. "time"
  9. )
  10. var log *logrus.Logger
  11. type RotateConfig struct {
  12. MaxAge time.Duration //最大时间
  13. RotationTime time.Duration //分隔间隔
  14. }
  15. type RotateOption func(config *RotateConfig)
  16. func WithMaxAge(age time.Duration) RotateOption {
  17. return func(q *RotateConfig) {
  18. q.MaxAge = age
  19. }
  20. }
  21. func WithRotationTime(roTime time.Duration) RotateOption {
  22. return func(config *RotateConfig) {
  23. config.RotationTime = roTime
  24. }
  25. }
  26. func NewLoggerByLogName(path string, options ...RotateOption) (*logrus.Logger, error) {
  27. co := &RotateConfig{MaxAge: 24 * 31 * 12 * time.Hour * 2, RotationTime: 7 * 24 * time.Hour}
  28. for _, v := range options {
  29. v(co)
  30. }
  31. writer, err := rotatelogs.New(
  32. path+"log.%Y%m%d%H%M%S",
  33. rotatelogs.WithLinkName(path),
  34. rotatelogs.WithMaxAge(co.MaxAge),
  35. rotatelogs.WithRotationTime(co.RotationTime),
  36. )
  37. if err != nil {
  38. return nil, err
  39. }
  40. return NewLogger(writer), err
  41. }
  42. func NewLogger(f io.Writer) *logrus.Logger {
  43. log = logrus.New()
  44. log.Formatter = &logrus.JSONFormatter{}
  45. //f, err := os.OpenFile("./log/log.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
  46. //if err != nil {
  47. // panic("不能打开日志文件 " + err.Error())
  48. //}
  49. customF := new(logrus.JSONFormatter)
  50. customF.TimestampFormat = "2006-01-02 15:04:05"
  51. log.SetFormatter(customF)
  52. log.SetLevel(logrus.DebugLevel)
  53. //log.Out = f
  54. log.Out = f
  55. return log
  56. }
  57. func GetErrorFuncInfo(skip int) string {
  58. pc, file, lineNo, ok := runtime.Caller(skip)
  59. if !ok {
  60. return ""
  61. }
  62. funcName := runtime.FuncForPC(pc).Name()
  63. //fileName := path.Base(file) // Base函数返回路径的最后一个元素
  64. return "文件名:" + file + " 行号:" + strconv.Itoa(lineNo) + " 方法名:" + funcName
  65. }