日志,我只想保留1周,怎么設(shè)置
日志,我只想保留1周,怎么設(shè)置
你是用的是webman還是workerman?
workerman我的方案是使用定時(shí)任務(wù)執(zhí)行一個(gè)PHP腳本,將日志每隔三天截下來保存到ftp空間中。定時(shí)任務(wù)我用的寶塔的GET定時(shí)任務(wù)。
如果頻率更高可以用workerman單開一個(gè)單線程worker,用定時(shí)器,掛載更多你想要的任務(wù)。
注意:未經(jīng)過驗(yàn)證。
參考了http://www.wtbis.cn/a/1600
在參考中的代碼的基礎(chǔ)上:
修改MonologExtendHandler.php:
protected function rotate()
{
if ($this->maxFileSize === 0) {
return;
}
$dateDir = date('Ym') . '/';
$logBasePath = empty($this->channelDirName) ? $this->runtimeLogPath . $dateDir : $this->runtimeLogPath . $this->channelDirName . '/' . $dateDir;
$filename = date('d').'.log';
$fullLogFilename = $logBasePath . $filename;
// archive latest file
clearstatcache(true, $fullLogFilename);
if (file_exists($fullLogFilename)) {
$target = $logBasePath. time() . '_' . $filename;
rename($fullLogFilename, $target);
} else {
if (!is_dir($logBasePath)) {
mkdir($logBasePath, 0755, true);
}
$this->url = $fullLogFilename;
}
// 新增:清理7天前的日志文件
$this->cleanOldLogs($logBasePath);
$this->mustRotate = false;
}
/**
* 清理7天前的日志文件
* @param string $logBasePath 日志目錄
*/
protected function cleanOldLogs(string $logBasePath)
{
$daysToKeep = 7; // 保留天數(shù)
$cutoffTime = time() - ($daysToKeep * 86400); // 7天前的時(shí)間戳
try {
$files = glob($logBasePath . '*.log');
foreach ($files as $file) {
if (filemtime($file) < $cutoffTime) {
@unlink($file);
}
}
// 清理空目錄
$this->removeEmptySubdirectories(dirname($logBasePath));
} catch (\Exception $e) {
// 避免清理失敗影響主流程
error_log('Clean old logs failed: ' . $e->getMessage());
}
}
/**
* 遞歸刪除空目錄
* @param string $dir 目錄路徑
*/
protected function removeEmptySubdirectories(string $dir)
{
if (!is_dir($dir)) {
return;
}
$items = scandir($dir);
foreach ($items as $item) {
if ($item === '.' || $item === '..') {
continue;
}
$path = $dir . DIRECTORY_SEPARATOR . $item;
if (is_dir($path)) {
$this->removeEmptySubdirectories($path);
@rmdir($path); // 嘗試刪除空目錄
}
}
}