日志,我只想保留1周,怎么设置 日志,我只想保留1周,怎么设置
你是用的是webman还是workerman?
workerman我的方案是使用定时任务执行一个PHP脚本,将日志每隔三天截下来保存到ftp空间中。定时任务我用的宝塔的GET定时任务。
如果频率更高可以用workerman单开一个单线程worker,用定时器,挂载更多你想要的任务。
webman
注意:未经过验证。 参考了https://www.workerman.net/a/1600
在参考中的代码的基础上: 修改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; // 保留天数 $cutoffTime = time() - ($daysToKeep * 86400); // 7天前的时间戳 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); // 尝试删除空目录 } } }
但我还是建议写一个原生的PHP脚本,在深夜进行file操作。可以用宝塔的GET定时任务触发。
官网已经写的很清楚了 https://www.workerman.net/doc/webman/config.html
你是用的是webman还是workerman?
workerman我的方案是使用定时任务执行一个PHP脚本,将日志每隔三天截下来保存到ftp空间中。定时任务我用的宝塔的GET定时任务。
如果频率更高可以用workerman单开一个单线程worker,用定时器,挂载更多你想要的任务。
webman
注意:未经过验证。
参考了https://www.workerman.net/a/1600
在参考中的代码的基础上:
修改MonologExtendHandler.php:
但我还是建议写一个原生的PHP脚本,在深夜进行file操作。可以用宝塔的GET定时任务触发。
官网已经写的很清楚了

https://www.workerman.net/doc/webman/config.html