Browse Source

logging: call pruneFiles on startup

To ensure that files are pruned before a new one is created.

Also clean up the logic in pruneFiles
pull/9012/head
Daniel Nephin 4 years ago
parent
commit
2dcc6966fe
  1. 30
      logging/logfile.go
  2. 3
      logging/logger.go

30
logging/logfile.go

@ -93,23 +93,27 @@ func (l *LogFile) pruneFiles() error {
if l.MaxFiles == 0 { if l.MaxFiles == 0 {
return nil return nil
} }
pattern := l.fileNamePattern()
//get all the files that match the log file pattern pattern := filepath.Join(l.logPath, fmt.Sprintf(l.fileNamePattern(), "*"))
globExpression := filepath.Join(l.logPath, fmt.Sprintf(pattern, "*")) matches, err := filepath.Glob(pattern)
matches, err := filepath.Glob(globExpression)
if err != nil { if err != nil {
return err return err
} }
var stale int
if l.MaxFiles <= -1 { switch {
// Prune everything case l.MaxFiles < 0:
stale = len(matches) return removeFiles(matches)
} else { case len(matches) < l.MaxFiles:
// Prune if there are more files stored than the configured max return nil
stale = len(matches) - l.MaxFiles
} }
for i := 0; i < stale; i++ {
if err := os.Remove(matches[i]); err != nil { last := len(matches) - l.MaxFiles
return removeFiles(matches[:last])
}
func removeFiles(files []string) error {
for _, file := range files {
if err := os.Remove(file); err != nil {
return err return err
} }
} }

3
logging/logger.go

@ -92,6 +92,9 @@ func Setup(config Config, out io.Writer) (hclog.InterceptLogger, error) {
MaxBytes: config.LogRotateBytes, MaxBytes: config.LogRotateBytes,
MaxFiles: config.LogRotateMaxFiles, MaxFiles: config.LogRotateMaxFiles,
} }
if err := logFile.pruneFiles(); err != nil {
return nil, fmt.Errorf("Failed to prune log files: %w", err)
}
if err := logFile.openNew(); err != nil { if err := logFile.openNew(); err != nil {
return nil, fmt.Errorf("Failed to setup logging: %w", err) return nil, fmt.Errorf("Failed to setup logging: %w", err)
} }

Loading…
Cancel
Save