蛋蛋星球 后台端
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.

1 月之前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package logx
  2. import (
  3. "bytes"
  4. "io"
  5. "os"
  6. "path/filepath"
  7. "time"
  8. "gopkg.in/natefinch/lumberjack.v2"
  9. )
  10. // output interface
  11. type WriteSyncer interface {
  12. io.Writer
  13. Sync() error
  14. }
  15. // split writer
  16. func NewRollingFile(dir, filename string, maxSize, MaxAge int) WriteSyncer {
  17. s, err := os.Stat(dir)
  18. if err != nil || !s.IsDir() {
  19. os.RemoveAll(dir)
  20. if err := os.MkdirAll(dir, 0766); err != nil {
  21. panic(err)
  22. }
  23. }
  24. return newLumberjackWriteSyncer(&lumberjack.Logger{
  25. Filename: filepath.Join(dir, filename),
  26. MaxSize: maxSize, // megabytes, MB
  27. MaxAge: MaxAge, // days
  28. LocalTime: true,
  29. Compress: false,
  30. })
  31. }
  32. type lumberjackWriteSyncer struct {
  33. *lumberjack.Logger
  34. buf *bytes.Buffer
  35. logChan chan []byte
  36. closeChan chan interface{}
  37. maxSize int
  38. }
  39. func newLumberjackWriteSyncer(l *lumberjack.Logger) *lumberjackWriteSyncer {
  40. ws := &lumberjackWriteSyncer{
  41. Logger: l,
  42. buf: bytes.NewBuffer([]byte{}),
  43. logChan: make(chan []byte, 5000),
  44. closeChan: make(chan interface{}),
  45. maxSize: 1024,
  46. }
  47. go ws.run()
  48. return ws
  49. }
  50. func (l *lumberjackWriteSyncer) run() {
  51. ticker := time.NewTicker(1 * time.Second)
  52. for {
  53. select {
  54. case <-ticker.C:
  55. if l.buf.Len() > 0 {
  56. l.sync()
  57. }
  58. case bs := <-l.logChan:
  59. _, err := l.buf.Write(bs)
  60. if err != nil {
  61. continue
  62. }
  63. if l.buf.Len() > l.maxSize {
  64. l.sync()
  65. }
  66. case <-l.closeChan:
  67. l.sync()
  68. return
  69. }
  70. }
  71. }
  72. func (l *lumberjackWriteSyncer) Stop() {
  73. close(l.closeChan)
  74. }
  75. func (l *lumberjackWriteSyncer) Write(bs []byte) (int, error) {
  76. b := make([]byte, len(bs))
  77. for i, c := range bs {
  78. b[i] = c
  79. }
  80. l.logChan <- b
  81. return 0, nil
  82. }
  83. func (l *lumberjackWriteSyncer) Sync() error {
  84. return nil
  85. }
  86. func (l *lumberjackWriteSyncer) sync() error {
  87. defer l.buf.Reset()
  88. _, err := l.Logger.Write(l.buf.Bytes())
  89. if err != nil {
  90. return err
  91. }
  92. return nil
  93. }