rotatelogger.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. return
  165. }
  166. defer func() {
  167. if r := recover(); r != nil {
  168. ErrorStack(r)
  169. }
  170. }()
  171. compressLogFile(file)
  172. }
  173. func (l *RotateLogger) maybeDeleteOutdatedFiles() {
  174. files := l.rule.OutdatedFiles()
  175. for _, file := range files {
  176. if err := os.Remove(file); err != nil {
  177. Errorf("failed to remove outdated file: %s", file)
  178. }
  179. }
  180. }
  181. func (l *RotateLogger) postRotate(file string) {
  182. go func() {
  183. // we cannot use threading.GoSafe here, because of import cycle.
  184. l.maybeCompressFile(file)
  185. l.maybeDeleteOutdatedFiles()
  186. }()
  187. }
  188. func (l *RotateLogger) rotate() error {
  189. if l.fp != nil {
  190. err := l.fp.Close()
  191. l.fp = nil
  192. if err != nil {
  193. return err
  194. }
  195. }
  196. _, err := os.Stat(l.filename)
  197. if err == nil && len(l.backup) > 0 {
  198. backupFilename := l.getBackupFilename()
  199. err = os.Rename(l.filename, backupFilename)
  200. if err != nil {
  201. return err
  202. }
  203. l.postRotate(backupFilename)
  204. }
  205. l.backup = l.rule.BackupFileName()
  206. if l.fp, err = os.Create(l.filename); err == nil {
  207. fs.CloseOnExec(l.fp)
  208. }
  209. return err
  210. }
  211. func (l *RotateLogger) startWorker() {
  212. l.waitGroup.Add(1)
  213. go func() {
  214. defer l.waitGroup.Done()
  215. for {
  216. select {
  217. case event := <-l.channel:
  218. l.write(event)
  219. case <-l.done:
  220. return
  221. }
  222. }
  223. }()
  224. }
  225. func (l *RotateLogger) write(v []byte) {
  226. if l.rule.ShallRotate() {
  227. if err := l.rotate(); err != nil {
  228. log.Println(err)
  229. } else {
  230. l.rule.MarkRotated()
  231. }
  232. }
  233. if l.fp != nil {
  234. l.fp.Write(v)
  235. }
  236. }
  237. func compressLogFile(file string) {
  238. start := timex.Now()
  239. Infof("compressing log file: %s", file)
  240. if err := gzipFile(file); err != nil {
  241. Errorf("compress error: %s", err)
  242. } else {
  243. Infof("compressed log file: %s, took %s", file, timex.Since(start))
  244. }
  245. }
  246. func getNowDate() string {
  247. return time.Now().Format(dateFormat)
  248. }
  249. func gzipFile(file string) error {
  250. in, err := os.Open(file)
  251. if err != nil {
  252. return err
  253. }
  254. defer in.Close()
  255. out, err := os.Create(fmt.Sprintf("%s.gz", file))
  256. if err != nil {
  257. return err
  258. }
  259. defer out.Close()
  260. w := gzip.NewWriter(out)
  261. if _, err = io.Copy(w, in); err != nil {
  262. return err
  263. } else if err = w.Close(); err != nil {
  264. return err
  265. }
  266. return os.Remove(file)
  267. }