rotatelogger.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. package logx
  2. import (
  3. "compress/gzip"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "log"
  8. "os"
  9. "path"
  10. "path/filepath"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/tal-tech/go-zero/core/fs"
  15. "github.com/tal-tech/go-zero/core/lang"
  16. "github.com/tal-tech/go-zero/core/timex"
  17. )
  18. const (
  19. dateFormat = "2006-01-02"
  20. hoursPerDay = 24
  21. bufferSize = 100
  22. defaultDirMode = 0755
  23. defaultFileMode = 0600
  24. )
  25. var ErrLogFileClosed = errors.New("error: log file closed")
  26. type (
  27. RotateRule interface {
  28. BackupFileName() string
  29. MarkRotated()
  30. OutdatedFiles() []string
  31. ShallRotate() bool
  32. }
  33. RotateLogger struct {
  34. filename string
  35. backup string
  36. fp *os.File
  37. channel chan []byte
  38. done chan lang.PlaceholderType
  39. rule RotateRule
  40. compress bool
  41. keepDays int
  42. // can't use threading.RoutineGroup because of cycle import
  43. waitGroup sync.WaitGroup
  44. closeOnce sync.Once
  45. }
  46. DailyRotateRule struct {
  47. rotatedTime string
  48. filename string
  49. delimiter string
  50. days int
  51. gzip bool
  52. }
  53. )
  54. func DefaultRotateRule(filename, delimiter string, days int, gzip bool) RotateRule {
  55. return &DailyRotateRule{
  56. rotatedTime: getNowDate(),
  57. filename: filename,
  58. delimiter: delimiter,
  59. days: days,
  60. gzip: gzip,
  61. }
  62. }
  63. func (r *DailyRotateRule) BackupFileName() string {
  64. return fmt.Sprintf("%s%s%s", r.filename, r.delimiter, getNowDate())
  65. }
  66. func (r *DailyRotateRule) MarkRotated() {
  67. r.rotatedTime = getNowDate()
  68. }
  69. func (r *DailyRotateRule) OutdatedFiles() []string {
  70. if r.days <= 0 {
  71. return nil
  72. }
  73. var pattern string
  74. if r.gzip {
  75. pattern = fmt.Sprintf("%s%s*.gz", r.filename, r.delimiter)
  76. } else {
  77. pattern = fmt.Sprintf("%s%s*", r.filename, r.delimiter)
  78. }
  79. files, err := filepath.Glob(pattern)
  80. if err != nil {
  81. Errorf("failed to delete outdated log files, error: %s", err)
  82. return nil
  83. }
  84. var buf strings.Builder
  85. boundary := time.Now().Add(-time.Hour * time.Duration(hoursPerDay*r.days)).Format(dateFormat)
  86. fmt.Fprintf(&buf, "%s%s%s", r.filename, r.delimiter, boundary)
  87. if r.gzip {
  88. buf.WriteString(".gz")
  89. }
  90. boundaryFile := buf.String()
  91. var outdates []string
  92. for _, file := range files {
  93. if file < boundaryFile {
  94. outdates = append(outdates, file)
  95. }
  96. }
  97. return outdates
  98. }
  99. func (r *DailyRotateRule) ShallRotate() bool {
  100. return len(r.rotatedTime) > 0 && getNowDate() != r.rotatedTime
  101. }
  102. func NewLogger(filename string, rule RotateRule, compress bool) (*RotateLogger, error) {
  103. l := &RotateLogger{
  104. filename: filename,
  105. channel: make(chan []byte, bufferSize),
  106. done: make(chan lang.PlaceholderType),
  107. rule: rule,
  108. compress: compress,
  109. }
  110. if err := l.init(); err != nil {
  111. return nil, err
  112. }
  113. l.startWorker()
  114. return l, nil
  115. }
  116. func (l *RotateLogger) Close() error {
  117. var err error
  118. l.closeOnce.Do(func() {
  119. close(l.done)
  120. l.waitGroup.Wait()
  121. if err = l.fp.Sync(); err != nil {
  122. return
  123. }
  124. err = l.fp.Close()
  125. })
  126. return err
  127. }
  128. func (l *RotateLogger) Write(data []byte) (int, error) {
  129. select {
  130. case l.channel <- data:
  131. return len(data), nil
  132. case <-l.done:
  133. log.Println(string(data))
  134. return 0, ErrLogFileClosed
  135. }
  136. }
  137. func (l *RotateLogger) getBackupFilename() string {
  138. if len(l.backup) == 0 {
  139. return l.rule.BackupFileName()
  140. } else {
  141. return l.backup
  142. }
  143. }
  144. func (l *RotateLogger) init() error {
  145. l.backup = l.rule.BackupFileName()
  146. if _, err := os.Stat(l.filename); err != nil {
  147. basePath := path.Dir(l.filename)
  148. if _, err = os.Stat(basePath); err != nil {
  149. if err = os.MkdirAll(basePath, defaultDirMode); err != nil {
  150. return err
  151. }
  152. }
  153. if l.fp, err = os.Create(l.filename); err != nil {
  154. return err
  155. }
  156. } else if l.fp, err = os.OpenFile(l.filename, os.O_APPEND|os.O_WRONLY, defaultFileMode); err != nil {
  157. return err
  158. }
  159. fs.CloseOnExec(l.fp)
  160. return nil
  161. }
  162. func (l *RotateLogger) maybeCompressFile(file string) {
  163. if l.compress {
  164. defer func() {
  165. if r := recover(); r != nil {
  166. ErrorStack(r)
  167. }
  168. }()
  169. compressLogFile(file)
  170. }
  171. }
  172. func (l *RotateLogger) maybeDeleteOutdatedFiles() {
  173. files := l.rule.OutdatedFiles()
  174. for _, file := range files {
  175. if err := os.Remove(file); err != nil {
  176. Errorf("failed to remove outdated file: %s", file)
  177. }
  178. }
  179. }
  180. func (l *RotateLogger) postRotate(file string) {
  181. go func() {
  182. // we cannot use threading.GoSafe here, because of import cycle.
  183. l.maybeCompressFile(file)
  184. l.maybeDeleteOutdatedFiles()
  185. }()
  186. }
  187. func (l *RotateLogger) rotate() error {
  188. if l.fp != nil {
  189. err := l.fp.Close()
  190. l.fp = nil
  191. if err != nil {
  192. return err
  193. }
  194. }
  195. _, err := os.Stat(l.filename)
  196. if err == nil && len(l.backup) > 0 {
  197. backupFilename := l.getBackupFilename()
  198. err = os.Rename(l.filename, backupFilename)
  199. if err != nil {
  200. return err
  201. }
  202. l.postRotate(backupFilename)
  203. }
  204. l.backup = l.rule.BackupFileName()
  205. if l.fp, err = os.Create(l.filename); err == nil {
  206. fs.CloseOnExec(l.fp)
  207. }
  208. return err
  209. }
  210. func (l *RotateLogger) startWorker() {
  211. l.waitGroup.Add(1)
  212. go func() {
  213. defer l.waitGroup.Done()
  214. for {
  215. select {
  216. case event := <-l.channel:
  217. l.write(event)
  218. case <-l.done:
  219. return
  220. }
  221. }
  222. }()
  223. }
  224. func (l *RotateLogger) write(v []byte) {
  225. if l.rule.ShallRotate() {
  226. if err := l.rotate(); err != nil {
  227. log.Println(err)
  228. } else {
  229. l.rule.MarkRotated()
  230. }
  231. }
  232. if l.fp != nil {
  233. l.fp.Write(v)
  234. }
  235. }
  236. func compressLogFile(file string) {
  237. start := timex.Now()
  238. Infof("compressing log file: %s", file)
  239. if err := gzipFile(file); err != nil {
  240. Errorf("compress error: %s", err)
  241. } else {
  242. Infof("compressed log file: %s, took %s", file, timex.Since(start))
  243. }
  244. }
  245. func getNowDate() string {
  246. return time.Now().Format(dateFormat)
  247. }
  248. func gzipFile(file string) error {
  249. in, err := os.Open(file)
  250. if err != nil {
  251. return err
  252. }
  253. defer in.Close()
  254. out, err := os.Create(fmt.Sprintf("%s.gz", file))
  255. if err != nil {
  256. return err
  257. }
  258. defer out.Close()
  259. w := gzip.NewWriter(out)
  260. if _, err = io.Copy(w, in); err != nil {
  261. return err
  262. } else if err = w.Close(); err != nil {
  263. return err
  264. }
  265. return os.Remove(file)
  266. }