|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Prokl\BitrixOrdinaryToolsBundle\Services\ErrorHandler; |
| 4 | + |
| 5 | +use Bitrix\Main\Application; |
| 6 | +use Bitrix\Main\ArgumentException; |
| 7 | +use Bitrix\Main\Diag\ExceptionHandlerLog; |
| 8 | +use Bitrix\Main\Entity\Base; |
| 9 | +use Bitrix\Main\ObjectPropertyException; |
| 10 | +use Bitrix\Main\SystemException; |
| 11 | +use Bitrix\Main\Type\DateTime; |
| 12 | +use Exception; |
| 13 | +use Bitrix\Main\Config\Option; |
| 14 | +use Prokl\BitrixOrdinaryToolsBundle\Services\Email\EventBridge\Notifier\BitrixNotification; |
| 15 | +use Prokl\BitrixOrdinaryToolsBundle\Services\ErrorHandler\Entity\ErrorLogTable; |
| 16 | +use RuntimeException; |
| 17 | +use Symfony\Component\Notifier\Notification\Notification; |
| 18 | +use Symfony\Component\Notifier\NotifierInterface; |
| 19 | +use Symfony\Component\Notifier\Recipient\Recipient; |
| 20 | + |
| 21 | +/** |
| 22 | + * Class ErrorHandler |
| 23 | + * @package Prokl\BitrixOrdinaryToolsBundle\Services\ErrorHandler |
| 24 | + * |
| 25 | + * @since 01.08.2021 |
| 26 | + */ |
| 27 | +class ErrorHandler extends ExceptionHandlerLog |
| 28 | +{ |
| 29 | + private const OPTION_TYPES = 'types'; |
| 30 | + |
| 31 | + /** |
| 32 | + * @var boolean[] $logTypeFlags |
| 33 | + */ |
| 34 | + private $logTypeFlags; |
| 35 | + |
| 36 | + /** |
| 37 | + * @var array $options |
| 38 | + */ |
| 39 | + private $options = []; |
| 40 | + |
| 41 | + /** |
| 42 | + * ErrorHandler constructor. |
| 43 | + */ |
| 44 | + public function __construct() |
| 45 | + { |
| 46 | + /** |
| 47 | + * По-умолчанию логируется всё, кроме LOW_PRIORITY_ERROR. |
| 48 | + * Этот тип ошибки засоряет логи и появляется не только часто, |
| 49 | + * но и происходит от ошибок в коде ядра Битрикс. |
| 50 | + */ |
| 51 | + $this->logTypeFlags = [ |
| 52 | + self::UNCAUGHT_EXCEPTION => true, |
| 53 | + self::CAUGHT_EXCEPTION => true, |
| 54 | + self::ASSERTION => true, |
| 55 | + self::FATAL => true, |
| 56 | + ]; |
| 57 | + |
| 58 | + $this->setUp(); |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * @inheritdoc |
| 63 | + */ |
| 64 | + public function initialize(array $options) |
| 65 | + { |
| 66 | + $this->initTypes($options); |
| 67 | + |
| 68 | + $this->options = $options; |
| 69 | + $this->initOptions(); |
| 70 | + } |
| 71 | + |
| 72 | + /** |
| 73 | + * @inheritdoc |
| 74 | + * @throws ArgumentException | SystemException |
| 75 | + * @throws Exception |
| 76 | + */ |
| 77 | + public function write($exception, $logType) |
| 78 | + { |
| 79 | + if ((!array_key_exists($logType, $this->logTypeFlags) |
| 80 | + || true !== $this->logTypeFlags[$logType]) |
| 81 | + || |
| 82 | + !in_array($this->options['env'], $this->options['allowed_env'], true) |
| 83 | + ) { |
| 84 | + return; |
| 85 | + } |
| 86 | + |
| 87 | + if ($exception instanceof Exception && !$this->has($exception)) { |
| 88 | + $this->send($exception); |
| 89 | + |
| 90 | + ErrorLogTable::add( |
| 91 | + [ |
| 92 | + 'DATE_CREATE' => new DateTime(), |
| 93 | + 'MD5' => md5(serialize($exception)), |
| 94 | + 'EXCEPTION' => serialize($exception), |
| 95 | + ] |
| 96 | + ); |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + /** |
| 101 | + * Экземпляр notifier. |
| 102 | + * |
| 103 | + * @return NotifierInterface |
| 104 | + */ |
| 105 | + private function getNotifier() : NotifierInterface |
| 106 | + { |
| 107 | + return container()->get('notifier'); |
| 108 | + } |
| 109 | + |
| 110 | + /** |
| 111 | + * Отправка уведомлений. |
| 112 | + * |
| 113 | + * @param Exception $exception |
| 114 | + * |
| 115 | + * @return void |
| 116 | + * @throws Exception |
| 117 | + */ |
| 118 | + private function send(Exception $exception) : void |
| 119 | + { |
| 120 | + $notifier = $this->getNotifier(); |
| 121 | + $importancy = $this->options['importancy']; |
| 122 | + |
| 123 | + $emails = container()->getParameter('mailer_recipients'); |
| 124 | + if (!$emails) { |
| 125 | + throw new RuntimeException('Email of recipitients not setting.'); |
| 126 | + } |
| 127 | + |
| 128 | + $email = $emails[0]; |
| 129 | + |
| 130 | + if ($this->options['recipient']) { |
| 131 | + $email = (string)$this->options['recipient']; |
| 132 | + } |
| 133 | + |
| 134 | + $request = Application::getInstance()->getContext()->getRequest(); |
| 135 | + $uriString = $request->getRequestUri(); |
| 136 | + |
| 137 | + $title = $request->getServer()->getServerName(); |
| 138 | + if (!$title) { |
| 139 | + $title = Option::get('main', 'server_name', ''); |
| 140 | + } |
| 141 | + |
| 142 | + $body = 'Url: ' . $uriString . ' '; |
| 143 | + $body = $body . get_class($exception) . |
| 144 | + ': ' . $exception->getMessage() . |
| 145 | + ' in ' . $exception->getFile() . |
| 146 | + ' at line ' . $exception->getLine(); |
| 147 | + |
| 148 | + $notification = (new BitrixNotification($title)) |
| 149 | + ->content($body) |
| 150 | + ->importance($importancy); |
| 151 | + |
| 152 | + $notifier->send($notification, new Recipient($email)); |
| 153 | + } |
| 154 | + |
| 155 | + /** |
| 156 | + * Есть запись о такой ошибке в таблице? |
| 157 | + * |
| 158 | + * @param Exception $e Ошибка. |
| 159 | + * |
| 160 | + * @return boolean |
| 161 | + * |
| 162 | + * @throws ArgumentException | SystemException | ObjectPropertyException ORM ошибки. |
| 163 | + */ |
| 164 | + private function has(Exception $e) : bool |
| 165 | + { |
| 166 | + $hash = md5(serialize($e)); |
| 167 | + |
| 168 | + $query = ErrorLogTable::getList([ |
| 169 | + 'filter' => [ |
| 170 | + '=MD5' => $hash |
| 171 | + ] |
| 172 | + ]); |
| 173 | + |
| 174 | + return count($query->fetchAll()) > 0; |
| 175 | + } |
| 176 | + |
| 177 | + /** |
| 178 | + * Инициализация типов обрабатываемых ошибок. |
| 179 | + * |
| 180 | + * @param array $options Опции. |
| 181 | + * |
| 182 | + * @return void |
| 183 | + */ |
| 184 | + private function initTypes(array $options) : void |
| 185 | + { |
| 186 | + if (!array_key_exists(self::OPTION_TYPES, $options) || !is_array($options[self::OPTION_TYPES])) { |
| 187 | + return; |
| 188 | + } |
| 189 | + |
| 190 | + $this->logTypeFlags = []; |
| 191 | + foreach ($options[self::OPTION_TYPES] as $logType) { |
| 192 | + if (is_int($logType)) { |
| 193 | + $this->logTypeFlags[$logType] = true; |
| 194 | + } |
| 195 | + } |
| 196 | + } |
| 197 | + |
| 198 | + /** |
| 199 | + * Обработка параметров. |
| 200 | + * |
| 201 | + * @return void |
| 202 | + */ |
| 203 | + private function initOptions(): void |
| 204 | + { |
| 205 | + $this->options['env'] = $this->options['env'] ?? 'prod'; |
| 206 | + |
| 207 | + $this->options['allowed_env'] = $this->options['allowed_env'] ?? ['prod']; |
| 208 | + if (count($this->options['allowed_env']) === 0) { |
| 209 | + $this->options['allowed_env'] = ['prod']; |
| 210 | + } |
| 211 | + |
| 212 | + $this->options['importancy'] = $this->options['importancy'] ?? Notification::IMPORTANCE_URGENT; |
| 213 | + } |
| 214 | + |
| 215 | + /** |
| 216 | + * Создать при необходимости таблицу и агента. |
| 217 | + * |
| 218 | + * @return void |
| 219 | + * @throws ArgumentException |
| 220 | + * @throws SystemException |
| 221 | + */ |
| 222 | + private function setUp(): void |
| 223 | + { |
| 224 | + // Создать таблицу b_fatal_error_log, если еще не. |
| 225 | + if (!Application::getConnection()->isTableExists( |
| 226 | + Base::getInstance(ErrorLogTable::class)->getDBTableName() |
| 227 | + )) { |
| 228 | + Base::getInstance(ErrorLogTable::class)->createDBTable(); |
| 229 | + } |
| 230 | + |
| 231 | + // Добавить агента, если еще нет. |
| 232 | + $rsAgents = \CAgent::getList([], |
| 233 | + ['NAME' => '\\Prokl\\BitrixOrdinaryToolsBundle\\Services\\ErrorHandler\\Agent\\ClearTableAgent::clear();']); |
| 234 | + if (!$rsAgents->fetch()) { |
| 235 | + \CAgent::AddAgent( |
| 236 | + '\\Prokl\\BitrixOrdinaryToolsBundle\\Services\\ErrorHandler\\Agent\\ClearTableAgent::clear();', |
| 237 | + '', |
| 238 | + 'N', |
| 239 | + 10 * 24 * 3600, |
| 240 | + '', |
| 241 | + 'Y', |
| 242 | + '' |
| 243 | + ); |
| 244 | + } |
| 245 | + } |
| 246 | +} |
0 commit comments