lumberjack_afero.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. // Derived from https://github.com/natefinch/lumberjack
  2. // Adapt filesystem to github.com/spf13/afero
  3. package lumberjack_afero
  4. import (
  5. "compress/gzip"
  6. "errors"
  7. "fmt"
  8. "github.com/spf13/afero"
  9. "io"
  10. "io/fs"
  11. "path/filepath"
  12. "sort"
  13. "strings"
  14. "sync"
  15. "time"
  16. )
  17. const (
  18. backupTimeFormat = "2006-01-02T15-04-05.000"
  19. compressSuffix = ".gz"
  20. defaultMaxSize = 100
  21. )
  22. // ensure we always implement io.WriteCloser
  23. var _ io.WriteCloser = (*Logger)(nil)
  24. // Logger is an io.WriteCloser that writes to the specified filename.
  25. //
  26. // Logger opens or creates the logfile on first Write. If the file exists and
  27. // is less than MaxSize megabytes, lumberjack will open and append to that file.
  28. // If the file exists and its size is >= MaxSize megabytes, the file is renamed
  29. // by putting the current time in a timestamp in the name immediately before the
  30. // file's extension (or the end of the filename if there's no extension). A new
  31. // log file is then created using original filename.
  32. //
  33. // Whenever a write would cause the current log file exceed MaxSize megabytes,
  34. // the current file is closed, renamed, and a new log file created with the
  35. // original name. Thus, the filename you give Logger is always the "current" log
  36. // file.
  37. //
  38. // Backups use the log file name given to Logger, in the form
  39. // `name-timestamp.ext` where name is the filename without the extension,
  40. // timestamp is the time at which the log was rotated formatted with the
  41. // time.Time format of `2006-01-02T15-04-05.000` and the extension is the
  42. // original extension. For example, if your Logger.Filename is
  43. // `/var/log/foo/server.log`, a backup created at 6:30pm on Nov 11 2016 would
  44. // use the filename `/var/log/foo/server-2016-11-04T18-30-00.000.log`
  45. //
  46. // # Cleaning Up Old Log Files
  47. //
  48. // Whenever a new logfile gets created, old log files may be deleted. The most
  49. // recent files according to the encoded timestamp will be retained, up to a
  50. // number equal to MaxBackups (or all of them if MaxBackups is 0). Any files
  51. // with an encoded timestamp older than MaxAge days are deleted, regardless of
  52. // MaxBackups. Note that the time encoded in the timestamp is the rotation
  53. // time, which may differ from the last time that file was written to.
  54. //
  55. // If MaxBackups and MaxAge are both 0, no old log files will be deleted.
  56. type Logger struct {
  57. // Filesystem is an afero.Fs Object to hold the logs.
  58. Filesystem afero.Fs
  59. // Filename is the file to write logs to. Backup log files will be retained
  60. // in the same directory. If not specified, will use `logs/<processname>.log`
  61. Filename string `json:"filename" yaml:"filename"`
  62. // MaxSize is the maximum size in megabytes of the log file before it gets
  63. // rotated. It defaults to 100 megabytes.
  64. MaxSize int `json:"maxsize" yaml:"maxsize"`
  65. // MaxAge is the maximum number of days to retain old log files based on the
  66. // timestamp encoded in their filename. Note that a day is defined as 24
  67. // hours and may not exactly correspond to calendar days due to daylight
  68. // savings, leap seconds, etc. The default is not to remove old log files
  69. // based on age.
  70. MaxAge int `json:"maxage" yaml:"maxage"`
  71. // MaxBackups is the maximum number of old log files to retain. The default
  72. // is to retain all old log files (though MaxAge may still cause them to get
  73. // deleted.)
  74. MaxBackups int `json:"maxbackups" yaml:"maxbackups"`
  75. // LocalTime determines if the time used for formatting the timestamps in
  76. // backup files is the computer's local time. The default is to use UTC
  77. // time.
  78. LocalTime bool `json:"localtime" yaml:"localtime"`
  79. // Compress determines if the rotated log files should be compressed
  80. // using gzip. The default is not to perform compression.
  81. Compress bool `json:"compress" yaml:"compress"`
  82. size int64
  83. file afero.File
  84. mu sync.Mutex
  85. millCh chan bool
  86. startMill sync.Once
  87. }
  88. var (
  89. // currentTime exists so it can be mocked out by tests.
  90. currentTime = time.Now
  91. // megabyte is the conversion factor between MaxSize and bytes. It is a
  92. // variable so tests can mock it out and not need to write megabytes of data
  93. // to disk.
  94. megabyte = 1024 * 1024
  95. )
  96. // Write implements io.Writer. If a write would cause the log file to be larger
  97. // than MaxSize, the file is closed, renamed to include a timestamp of the
  98. // current time, and a new log file is created using the original log file name.
  99. // If the length of the write is greater than MaxSize, an error is returned.
  100. func (l *Logger) Write(p []byte) (n int, err error) {
  101. l.mu.Lock()
  102. defer l.mu.Unlock()
  103. writeLen := int64(len(p))
  104. if writeLen > l.max() {
  105. return 0, fmt.Errorf(
  106. "write length %d exceeds maximum file size %d", writeLen, l.max(),
  107. )
  108. }
  109. if l.file == nil {
  110. if err = l.openExistingOrNew(len(p)); err != nil {
  111. return 0, err
  112. }
  113. }
  114. if l.size+writeLen > l.max() {
  115. if err := l.rotate(); err != nil {
  116. return 0, err
  117. }
  118. }
  119. n, err = l.file.Write(p)
  120. l.size += int64(n)
  121. return n, err
  122. }
  123. // Close implements io.Closer, and closes the current logfile.
  124. func (l *Logger) Close() error {
  125. l.mu.Lock()
  126. defer l.mu.Unlock()
  127. return l.close()
  128. }
  129. // close closes the file if it is open.
  130. func (l *Logger) close() error {
  131. if l.file == nil {
  132. return nil
  133. }
  134. err := l.file.Close()
  135. l.file = nil
  136. return err
  137. }
  138. // Rotate causes Logger to close the existing log file and immediately create a
  139. // new one. This is a helper function for applications that want to initiate
  140. // rotations outside of the normal rotation rules, such as in response to
  141. // SIGHUP. After rotating, this initiates compression and removal of old log
  142. // files according to the configuration.
  143. func (l *Logger) Rotate() error {
  144. l.mu.Lock()
  145. defer l.mu.Unlock()
  146. return l.rotate()
  147. }
  148. // rotate closes the current file, moves it aside with a timestamp in the name,
  149. // (if it exists), opens a new file with the original filename, and then runs
  150. // post-rotation processing and removal.
  151. func (l *Logger) rotate() error {
  152. if err := l.close(); err != nil {
  153. return err
  154. }
  155. if err := l.openNew(); err != nil {
  156. return err
  157. }
  158. l.mill()
  159. return nil
  160. }
  161. // openNew opens a new log file for writing, moving any old log file out of the
  162. // way. This methods assumes the file has already been closed.
  163. func (l *Logger) openNew() error {
  164. err := l.Filesystem.MkdirAll(l.dir(), 0755)
  165. if err != nil {
  166. return fmt.Errorf("can't make directories for new logfile: %s", err)
  167. }
  168. name := l.filename()
  169. mode := fs.FileMode(0600)
  170. info, err := l.Filesystem.Stat(name)
  171. if err == nil {
  172. // Copy the mode off the old logfile.
  173. mode = info.Mode()
  174. // move the existing file
  175. newname := backupName(name, l.LocalTime)
  176. if err := l.Filesystem.Rename(name, newname); err != nil {
  177. return fmt.Errorf("can't rename log file: %s", err)
  178. }
  179. }
  180. // we use truncate here because this should only get called when we've moved
  181. // the file ourselves. if someone else creates the file in the meantime,
  182. // just wipe out the contents.
  183. f, err := l.Filesystem.OpenFile(name, O_CREATE|O_WRONLY|O_TRUNC, mode)
  184. if err != nil {
  185. return fmt.Errorf("can't open new logfile: %s", err)
  186. }
  187. l.file = f
  188. l.size = 0
  189. return nil
  190. }
  191. // backupName creates a new filename from the given name, inserting a timestamp
  192. // between the filename and the extension, using the local time if requested
  193. // (otherwise UTC).
  194. func backupName(name string, local bool) string {
  195. dir := filepath.Dir(name)
  196. filename := filepath.Base(name)
  197. ext := filepath.Ext(filename)
  198. prefix := filename[:len(filename)-len(ext)]
  199. t := currentTime()
  200. if !local {
  201. t = t.UTC()
  202. }
  203. timestamp := t.Format(backupTimeFormat)
  204. return filepath.Join(dir, fmt.Sprintf("%s-%s%s", prefix, timestamp, ext))
  205. }
  206. // openExistingOrNew opens the logfile if it exists and if the current write
  207. // would not put it over MaxSize. If there is no such file or the write would
  208. // put it over the MaxSize, a new file is created.
  209. func (l *Logger) openExistingOrNew(writeLen int) error {
  210. l.mill()
  211. filename := l.filename()
  212. info, err := l.Filesystem.Stat(filename)
  213. if IsNotExist(err) {
  214. return l.openNew()
  215. }
  216. if err != nil {
  217. return fmt.Errorf("error getting log file info: %s", err)
  218. }
  219. if info.Size()+int64(writeLen) >= l.max() {
  220. return l.rotate()
  221. }
  222. file, err := l.Filesystem.OpenFile(filename, O_APPEND|O_WRONLY, 0644)
  223. if err != nil {
  224. // if we fail to open the old log file for some reason, just ignore
  225. // it and open a new log file.
  226. return l.openNew()
  227. }
  228. l.file = file
  229. l.size = info.Size()
  230. return nil
  231. }
  232. // filename generates the name of the logfile from the current time.
  233. func (l *Logger) filename() string {
  234. if l.Filename != "" {
  235. return l.Filename
  236. }
  237. name := getProcessName() + ".log"
  238. return filepath.Join("logs", name)
  239. }
  240. // millRunOnce performs compression and removal of stale log files.
  241. // Log files are compressed if enabled via configuration and old log
  242. // files are removed, keeping at most l.MaxBackups files, as long as
  243. // none of them are older than MaxAge.
  244. func (l *Logger) millRunOnce() error {
  245. if l.MaxBackups == 0 && l.MaxAge == 0 && !l.Compress {
  246. return nil
  247. }
  248. files, err := l.oldLogFiles()
  249. if err != nil {
  250. return err
  251. }
  252. var compress, remove []logInfo
  253. if l.MaxBackups > 0 && l.MaxBackups < len(files) {
  254. preserved := make(map[string]bool)
  255. var remaining []logInfo
  256. for _, f := range files {
  257. // Only count the uncompressed log file or the
  258. // compressed log file, not both.
  259. fn := f.Name()
  260. if strings.HasSuffix(fn, compressSuffix) {
  261. fn = fn[:len(fn)-len(compressSuffix)]
  262. }
  263. preserved[fn] = true
  264. if len(preserved) > l.MaxBackups {
  265. remove = append(remove, f)
  266. } else {
  267. remaining = append(remaining, f)
  268. }
  269. }
  270. files = remaining
  271. }
  272. if l.MaxAge > 0 {
  273. diff := time.Duration(int64(24*time.Hour) * int64(l.MaxAge))
  274. cutoff := currentTime().Add(-1 * diff)
  275. var remaining []logInfo
  276. for _, f := range files {
  277. if f.timestamp.Before(cutoff) {
  278. remove = append(remove, f)
  279. } else {
  280. remaining = append(remaining, f)
  281. }
  282. }
  283. files = remaining
  284. }
  285. if l.Compress {
  286. for _, f := range files {
  287. if !strings.HasSuffix(f.Name(), compressSuffix) {
  288. compress = append(compress, f)
  289. }
  290. }
  291. }
  292. for _, f := range remove {
  293. errRemove := l.Filesystem.Remove(filepath.Join(l.dir(), f.Name()))
  294. if err == nil && errRemove != nil {
  295. err = errRemove
  296. }
  297. }
  298. for _, f := range compress {
  299. fn := filepath.Join(l.dir(), f.Name())
  300. errCompress := l.compressLogFile(fn, fn+compressSuffix)
  301. if err == nil && errCompress != nil {
  302. err = errCompress
  303. }
  304. }
  305. return err
  306. }
  307. // millRun runs in a goroutine to manage post-rotation compression and removal
  308. // of old log files.
  309. func (l *Logger) millRun() {
  310. for range l.millCh {
  311. // what am I going to do, log this?
  312. _ = l.millRunOnce()
  313. }
  314. }
  315. // mill performs post-rotation compression and removal of stale log files,
  316. // starting the mill goroutine if necessary.
  317. func (l *Logger) mill() {
  318. l.startMill.Do(func() {
  319. l.millCh = make(chan bool, 1)
  320. go l.millRun()
  321. })
  322. select {
  323. case l.millCh <- true:
  324. default:
  325. }
  326. }
  327. // oldLogFiles returns the list of backup log files stored in the same
  328. // directory as the current log file, sorted by ModTime
  329. func (l *Logger) oldLogFiles() ([]logInfo, error) {
  330. files, err := afero.ReadDir(l.Filesystem, l.dir())
  331. if err != nil {
  332. return nil, fmt.Errorf("can't read log file directory: %s", err)
  333. }
  334. logFiles := []logInfo{}
  335. prefix, ext := l.prefixAndExt()
  336. for _, f := range files {
  337. if f.IsDir() {
  338. continue
  339. }
  340. if t, err := l.timeFromName(f.Name(), prefix, ext); err == nil {
  341. logFiles = append(logFiles, logInfo{t, f})
  342. continue
  343. }
  344. if t, err := l.timeFromName(f.Name(), prefix, ext+compressSuffix); err == nil {
  345. logFiles = append(logFiles, logInfo{t, f})
  346. continue
  347. }
  348. // error parsing means that the suffix at the end was not generated
  349. // by lumberjack, and therefore it's not a backup file.
  350. }
  351. sort.Sort(byFormatTime(logFiles))
  352. return logFiles, nil
  353. }
  354. // timeFromName extracts the formatted time from the filename by stripping off
  355. // the filename's prefix and extension. This prevents someone's filename from
  356. // confusing time.parse.
  357. func (l *Logger) timeFromName(filename, prefix, ext string) (time.Time, error) {
  358. if !strings.HasPrefix(filename, prefix) {
  359. return time.Time{}, errors.New("mismatched prefix")
  360. }
  361. if !strings.HasSuffix(filename, ext) {
  362. return time.Time{}, errors.New("mismatched extension")
  363. }
  364. ts := filename[len(prefix) : len(filename)-len(ext)]
  365. return time.Parse(backupTimeFormat, ts)
  366. }
  367. // max returns the maximum size in bytes of log files before rolling.
  368. func (l *Logger) max() int64 {
  369. if l.MaxSize == 0 {
  370. return int64(defaultMaxSize * megabyte)
  371. }
  372. return int64(l.MaxSize) * int64(megabyte)
  373. }
  374. // dir returns the directory for the current filename.
  375. func (l *Logger) dir() string {
  376. return filepath.Dir(l.filename())
  377. }
  378. // prefixAndExt returns the filename part and extension part from the Logger's
  379. // filename.
  380. func (l *Logger) prefixAndExt() (prefix, ext string) {
  381. filename := filepath.Base(l.filename())
  382. ext = filepath.Ext(filename)
  383. prefix = filename[:len(filename)-len(ext)] + "-"
  384. return prefix, ext
  385. }
  386. // compressLogFile compresses the given log file, removing the
  387. // uncompressed log file if successful.
  388. func (l *Logger) compressLogFile(src, dst string) (err error) {
  389. f, err := l.Filesystem.Open(src)
  390. if err != nil {
  391. return fmt.Errorf("failed to open log file: %v", err)
  392. }
  393. // noinspection GoUnhandledErrorResult
  394. defer f.Close()
  395. fi, err := l.Filesystem.Stat(src)
  396. if err != nil {
  397. return fmt.Errorf("failed to stat log file: %v", err)
  398. }
  399. // If this file already exists, we presume it was created by
  400. // a previous attempt to compress the log file.
  401. gzf, err := l.Filesystem.OpenFile(dst, O_CREATE|O_TRUNC|O_WRONLY, fi.Mode())
  402. if err != nil {
  403. return fmt.Errorf("failed to open compressed log file: %v", err)
  404. }
  405. // noinspection GoUnhandledErrorResult
  406. defer gzf.Close()
  407. gz := gzip.NewWriter(gzf)
  408. defer func() {
  409. if err != nil {
  410. _ = l.Filesystem.Remove(dst)
  411. err = fmt.Errorf("failed to compress log file: %v", err)
  412. }
  413. }()
  414. if _, err := io.Copy(gz, f); err != nil {
  415. return err
  416. }
  417. if err := gz.Close(); err != nil {
  418. return err
  419. }
  420. if err := gzf.Close(); err != nil {
  421. return err
  422. }
  423. if err := f.Close(); err != nil {
  424. return err
  425. }
  426. if err := l.Filesystem.Remove(src); err != nil {
  427. return err
  428. }
  429. return nil
  430. }
  431. // logInfo is a convenience struct to return the filename and its embedded
  432. // timestamp.
  433. type logInfo struct {
  434. timestamp time.Time
  435. fs.FileInfo
  436. }
  437. // byFormatTime sorts by newest time formatted in the name.
  438. type byFormatTime []logInfo
  439. func (b byFormatTime) Less(i, j int) bool {
  440. return b[i].timestamp.After(b[j].timestamp)
  441. }
  442. func (b byFormatTime) Swap(i, j int) {
  443. b[i], b[j] = b[j], b[i]
  444. }
  445. func (b byFormatTime) Len() int {
  446. return len(b)
  447. }