lumberjack.go 16 KB

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