feat: remove outdated log entries scheduled
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Command;
|
||||
|
||||
use App\Repository\LogEntryRepository;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Symfony\Component\Console\Style\SymfonyStyle;
|
||||
|
||||
#[AsCommand(
|
||||
name: 'app:cleanup:log-entries',
|
||||
description: 'Removes log entries older than the specified retention period'
|
||||
)]
|
||||
class CleanupLogEntriesCommand extends Command
|
||||
{
|
||||
private const DEFAULT_RETENTION_MONTHS = 6;
|
||||
|
||||
public function __construct(
|
||||
private readonly LogEntryRepository $logEntryRepository,
|
||||
private readonly LoggerInterface $logger,
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
protected function configure(): void
|
||||
{
|
||||
$this->addOption(
|
||||
'retention',
|
||||
'r',
|
||||
InputOption::VALUE_REQUIRED,
|
||||
'Retention period in months',
|
||||
(string) self::DEFAULT_RETENTION_MONTHS
|
||||
);
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$io = new SymfonyStyle($input, $output);
|
||||
|
||||
$retentionMonths = (int) $input->getOption('retention');
|
||||
if ($retentionMonths < 1) {
|
||||
$io->error('Retention period must be at least 1 month.');
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
$threshold = (new \DateTimeImmutable())->modify(sprintf('-%d months', $retentionMonths));
|
||||
|
||||
$deletedCount = $this->logEntryRepository->deleteOlderThan($threshold);
|
||||
|
||||
$message = sprintf(
|
||||
'Removed %d log entries older than %d month%s (before %s)',
|
||||
$deletedCount,
|
||||
$retentionMonths,
|
||||
1 === $retentionMonths ? '' : 's',
|
||||
$threshold->format('Y-m-d H:i:s')
|
||||
);
|
||||
|
||||
$this->logger->info($message);
|
||||
$io->success($message);
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user