Files
datahub/backend/app/Command/CleanRequestLogsCommand.php
T

47 lines
1.2 KiB
PHP
Raw Normal View History

2026-03-17 12:46:32 +08:00
<?php
declare(strict_types=1);
namespace App\Command;
use App\Model\ApiRequestLog;
use Carbon\Carbon;
use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputOption;
#[Command]
class CleanRequestLogsCommand extends HyperfCommand
{
public function __construct(protected ContainerInterface $container)
{
parent::__construct('log:clean-requests');
}
public function configure(): void
{
parent::configure();
$this->setDescription('清理过期的 API 请求日志');
$this->addOption('days', 'd', InputOption::VALUE_OPTIONAL, '保留天数', 90);
}
public function handle(): void
{
$days = (int) $this->input->getOption('days');
2026-03-17 14:17:06 +08:00
if ($days < 1) {
$this->error('保留天数必须大于 0');
return;
}
2026-03-17 12:46:32 +08:00
$cutoff = Carbon::now()->subDays($days);
$deleted = ApiRequestLog::query()
->where('created_at', '<', $cutoff)
->delete();
$this->info("已清理 {$deleted} 条超过 {$days} 天的请求日志。");
}
}