Нет описания

LogHandler.php 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace MailPoet\Logging;
  3. if (!defined('ABSPATH')) exit;
  4. use MailPoet\Entities\LogEntity;
  5. use MailPoetVendor\Monolog\Handler\AbstractProcessingHandler;
  6. class LogHandler extends AbstractProcessingHandler {
  7. /**
  8. * Logs older than this many days will be deleted
  9. */
  10. const DAYS_TO_KEEP_LOGS = 30;
  11. /**
  12. * Percentage value, what is the probability of running purge routine
  13. * @var int
  14. */
  15. const LOG_PURGE_PROBABILITY = 5;
  16. /** @var callable|null */
  17. private $randFunction;
  18. /** @var LogRepository */
  19. private $logRepository;
  20. public function __construct(
  21. LogRepository $logRepository,
  22. $level = \MailPoetVendor\Monolog\Logger::DEBUG,
  23. $bubble = \true,
  24. $randFunction = null
  25. ) {
  26. parent::__construct($level, $bubble);
  27. $this->randFunction = $randFunction;
  28. $this->logRepository = $logRepository;
  29. }
  30. protected function write(array $record) {
  31. $entity = new LogEntity();
  32. $entity->setName($record['channel']);
  33. $entity->setLevel($record['level']);
  34. $entity->setMessage($record['formatted']);
  35. $entity->setCreatedAt($record['datetime']);
  36. $this->logRepository->persist($entity);
  37. $this->logRepository->flush();
  38. if ($this->getRandom() <= self::LOG_PURGE_PROBABILITY) {
  39. $this->purgeOldLogs();
  40. }
  41. }
  42. private function getRandom() {
  43. if ($this->randFunction) {
  44. return call_user_func($this->randFunction, 0, 100);
  45. }
  46. return rand(0, 100);
  47. }
  48. private function purgeOldLogs() {
  49. $this->logRepository->purgeOldLogs(self::DAYS_TO_KEEP_LOGS);
  50. }
  51. }