func CleanupLogFiles()

in agent/logging/agent_logging.go [97:135]


func CleanupLogFiles(logFile string, maxFilesToKeep int) {
	// if fileCount is zero clean up all the log files matching the logFile
	// pattern
	var logfilePattern string = fmt.Sprintf("%s.*", logFile)
	matches, err := filepath.Glob(logfilePattern)
	if err != nil {
		log.Warnf("Errors when attempting to match glob pattern: %s: [error %v]", logfilePattern, err)
		return
	}

	if len(matches) < maxFilesToKeep {
		return
	}

	// Sort the files in reverse chronological order (newest first)
	sort.Slice(matches, func(i, j int) bool {
		a_parts := strings.Split(matches[i], ".")
		b_parts := strings.Split(matches[j], ".")

		// If the filename does not end in an epoch bubble it to the end
		a_time, err := strconv.ParseInt(a_parts[len(a_parts)-1], 10, 64)
		if err != nil {
			return false
		}

		b_time, err := strconv.ParseInt(b_parts[len(b_parts)-1], 10, 64)
		if err != nil {
			return false
		}
		return a_time > b_time
	})

	for i, f := range matches {
		if i < maxFilesToKeep {
			continue
		}
		os.Remove(f)
	}
}