(logPath string, maxBackups int)
| 88 | } |
| 89 | |
| 90 | func (r *LogRotate) rotateLogFile(logPath string, maxBackups int) error { |
| 91 | // Rename the current log file |
| 92 | backupPath := logPath + "." + time.Now().Format("20060102-150405") |
| 93 | |
| 94 | err := os.Rename(logPath, backupPath) |
| 95 | if err != nil { |
| 96 | return err |
| 97 | } |
| 98 | |
| 99 | glob := logPath + ".*" |
| 100 | if r.Compress { |
| 101 | glob = logPath + ".*.gz" |
| 102 | err = compressFile(backupPath) |
| 103 | if err != nil { |
| 104 | return err |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | // Remove old backups |
| 109 | files, err := filepath.Glob(glob) |
| 110 | if err != nil { |
| 111 | return err |
| 112 | } |
| 113 | |
| 114 | sort.Sort(sort.Reverse(sort.StringSlice(files))) |
| 115 | |
| 116 | for i, file := range files { |
| 117 | logger.Trace("Checking file", "file", file, "index", i, "maxBackups", maxBackups) |
| 118 | if i >= maxBackups { |
| 119 | logger.Trace("Removing file as over max backup count", "file", file) |
| 120 | os.Remove(file) |
| 121 | } else { |
| 122 | // Check the age of the file |
| 123 | fileInfo, err := os.Stat(file) |
| 124 | if err != nil { |
| 125 | return err |
| 126 | } |
| 127 | age := time.Since(fileInfo.ModTime()).Hours() |
| 128 | if age > float64(r.MaxAge*24) { |
| 129 | logger.Trace("Removing file as age was over configured amount", "file", file, "age", age) |
| 130 | os.Remove(file) |
| 131 | } |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | return nil |
| 136 | } |
| 137 | |
| 138 | func compressFile(src string) error { |
| 139 | // Open the source file for reading |
no test coverage detected