Use doctrine to purge old logs

[MAILPOET-3624]
This commit is contained in:
Pavel Dohnal
2021-06-04 09:36:28 +02:00
committed by Veljko V
parent e661d07acb
commit e5e7be6437
2 changed files with 14 additions and 9 deletions

View File

@@ -3,11 +3,13 @@
namespace MailPoet\Logging; namespace MailPoet\Logging;
use MailPoet\Entities\LogEntity; use MailPoet\Entities\LogEntity;
use MailPoet\Models\Log;
use MailPoetVendor\Carbon\Carbon;
use MailPoetVendor\Monolog\Handler\AbstractProcessingHandler; use MailPoetVendor\Monolog\Handler\AbstractProcessingHandler;
class LogHandler extends AbstractProcessingHandler { class LogHandler extends AbstractProcessingHandler {
/**
* Logs older than this many days will be deleted
*/
const DAYS_TO_KEEP_LOGS = 30;
/** /**
* Percentage value, what is the probability of running purge routine * Percentage value, what is the probability of running purge routine
@@ -15,11 +17,6 @@ class LogHandler extends AbstractProcessingHandler {
*/ */
const LOG_PURGE_PROBABILITY = 5; const LOG_PURGE_PROBABILITY = 5;
/**
* Logs older than this many days will be deleted
*/
const DAYS_TO_KEEP_LOGS = 30;
/** @var callable|null */ /** @var callable|null */
private $randFunction; private $randFunction;
@@ -60,7 +57,6 @@ class LogHandler extends AbstractProcessingHandler {
} }
private function purgeOldLogs() { private function purgeOldLogs() {
Log::whereLt('created_at', Carbon::now()->subDays(self::DAYS_TO_KEEP_LOGS)->toDateTimeString()) $this->logRepository->purgeOldLogs(self::DAYS_TO_KEEP_LOGS);
->deleteMany();
} }
} }

View File

@@ -5,6 +5,7 @@ namespace MailPoet\Logging;
use MailPoet\Doctrine\Repository; use MailPoet\Doctrine\Repository;
use MailPoet\Entities\LogEntity; use MailPoet\Entities\LogEntity;
use MailPoet\Util\Helpers; use MailPoet\Util\Helpers;
use MailPoetVendor\Carbon\Carbon;
/** /**
* @extends Repository<LogEntity> * @extends Repository<LogEntity>
@@ -62,4 +63,12 @@ class LogRepository extends Repository {
return $query->getQuery()->getResult(); return $query->getQuery()->getResult();
} }
public function purgeOldLogs(int $daysToKeepLogs) {
$queryBuilder = $this->entityManager->createQueryBuilder();
return $queryBuilder->delete(LogEntity::class, 'l')
->where('l.createdAt < :days')
->setParameter('days', Carbon::now()->subDays($daysToKeepLogs)->toDateTimeString())
->getQuery()->execute();
}
} }