ThinkPHP6.0默认用monolog按天生成日志(如2024-05-20.log)于runtime/log/,无自动清理机制;需手动实现:①PHP脚本清理30天前日志;②Linux cron定时执行;③自定义think命令log:clear;注意权限、文件匹配和进程占用问题。

ThinkPHP6.0 默认使用 monolog 驱动记录日志,日志文件按天生成(如 2024-05-20.log),存放在 runtime/log/ 目录下。官方不提供自动清理机制,需自行编写脚本定期删除过期日志。
方式一:使用 PHP 命令行脚本(推荐)
在项目根目录下新建 clear_log.php,内容如下:
(清理 30 天前的日志文件)
<?php
// clear_log.php
define('APP_PATH', __DIR__ . '/app/');
define('RUNTIME_PATH', __DIR__ . '/runtime/');
require __DIR__ . '/vendor/autoload.php';
<p>$logPath = RUNTIME_PATH . 'log/';
$days = 30;
$cutoffTime = strtotime("-{$days} days");</p><p>if (is_dir($logPath)) {
$files = scandir($logPath);
foreach ($files as $file) {
if ($file === '.' || $file === '..') continue;
$filePath = $logPath . $file;
// 只处理 .log 文件,且文件名符合 Y-m-d 格式(如 2024-01-01.log)
if (pathinfo($file, PATHINFO_EXTENSION) === 'log' &&
preg_match('/^(\d{4}-\d{2}-\d{2}).log$/', $file, $m)) {
$logDate = strtotime($m[1]);
if ($logDate !== false && $logDate < $cutoffTime) {
@unlink($filePath);
echo "Deleted: {$file}\n";
}
}
}
}
echo "Log cleanup completed.\n";执行命令:
立即学习“PHP免费学习笔记(深入)”;
php clear_log.php
方式二:用 Linux cron 定时执行
将清理脚本加入系统定时任务,每天凌晨 2 点运行:
- 编辑 crontab:
crontab -e - 添加一行(替换为你的项目绝对路径):
0 2 * * * /usr/bin/php /var/www/myproject/clear_log.php >/dev/null 2>&1
方式三:集成到 ThinkPHP 命令行指令(可选)
创建自定义命令类 app/command/ClearLog.php:
namespace app\command;
<p>use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Env;</p><p>class ClearLog extends Command
{
protected function configure()
{
$this->setName('log:clear')
->setDescription('Clear old log files');
}</p><pre class="brush:php;toolbar:false;">protected function execute(Input $input, Output $output)
{
$logPath = Env::get('root_path') . 'runtime' . DIRECTORY_SEPARATOR . 'log' . DIRECTORY_SEPARATOR;
$days = 30;
$cutoff = strtotime("-{$days} days");
if (!is_dir($logPath)) {
$output->writeln('Log directory not found.');
return 1;
}
$files = glob($logPath . '*.log');
$deleted = 0;
foreach ($files as $file) {
$basename = basename($file);
if (preg_match('/^(\d{4}-\d{2}-\d{2})\.log$/', $basename, $m)) {
if (strtotime($m[1]) < $cutoff) {
@unlink($file);
$deleted++;
}
}
}
$output->writeln("Cleaned {$deleted} old log files.");
return 0;
}}
然后执行:php think log:clear
注意事项
- 确保
runtime/log/目录有写权限 - 避免误删当天或昨日日志,建议正则严格匹配
YYYY-MM-DD.log格式 - 生产环境建议先测试脚本,加
echo或日志记录确认删除行为 - 如使用 Swoole 或常驻进程,注意日志文件可能被占用,
unlink失败时可忽略或记录警告



















