面包店
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 

106 linhas
1.8 KiB

  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. }