使用如下所示的代码使日志目录中的文件随时间老化。MAX_LOG_FILE_AGE
可以计算或设置为任何期望的值。这将正确删除比期望的更早的文件。
问题产生于我收到的需求的变化,而不是只保留一定数量的最新文件,在我的情况下是三(3)。这如何实现?
long deleteDate = System.currentTimeMillis() - MAX_LOG_FILE_AGE
def ant = new AntBuilder()
ant.delete() {
fileset (dir: "${someParentDir}/logs/", includes: '**/*') {
date(millis: "${deleteDate}", when: 'before')
}
}
使用Ant很难做到这一点。但是在Groovy中,它是可处理的:
def MAX_LOG_FILE_AGE_IN_MILLIS = 24 * 60 * 60 * 1000
def deleteDate = System.currentTimeMillis() - MAX_LOG_FILE_AGE_IN_MILLIS
def logDir = "logs"
def logs = []
// build list of files
new File(logDir).eachFileRecurse { file ->
if (file.isFile() && (file.lastModified() < deleteDate)) {
logs << file
}
}
// sort by last modified (ascending)
def sortedLogs = logs.toSorted { a,b -> a.lastModified() <=> b.lastModified() }
// N most recent are skipped
def n = 3
def victims = sortedLogs.dropRight(n)
// delete victims
victims.each { victim ->
println "deleting $victim.name"
victim.delete()
}