From 01ed365662b11ddac27e4eca04d8b53a0830ed8f Mon Sep 17 00:00:00 2001 From: Zishan <3089863+Xinecraft@users.noreply.github.com> Date: Tue, 28 Feb 2023 20:55:37 +0530 Subject: [PATCH] fix: :bug: Add option to ignore thrown exceptions using .env variable (#35) --- README.md | 1 + src/DiscordLogger/LogHandler.php | 22 ++++++++++++++++++---- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 271ce7c..25bde1d 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,7 @@ You must add a new channel to your `config/logging.php` file: 'via' => MarvinLabs\DiscordLogger\Logger::class, 'level' => 'debug', 'url' => env('LOG_DISCORD_WEBHOOK_URL'), + 'ignore_exceptions' => env('LOG_DISCORD_IGNORE_EXCEPTIONS', false), ], ]; ``` diff --git a/src/DiscordLogger/LogHandler.php b/src/DiscordLogger/LogHandler.php index c23395f..bb5a35e 100644 --- a/src/DiscordLogger/LogHandler.php +++ b/src/DiscordLogger/LogHandler.php @@ -9,6 +9,7 @@ use MarvinLabs\DiscordLogger\Converters\SimpleRecordConverter; use Monolog\Handler\AbstractProcessingHandler; use Monolog\Logger as Monolog; +use Monolog\LogRecord; use RuntimeException; use function class_implements; @@ -20,6 +21,9 @@ class LogHandler extends AbstractProcessingHandler /** @var \MarvinLabs\DiscordLogger\Contracts\RecordToMessage */ private $recordToMessage; + /** @var boolean */ + private $ignoreExceptions; + /** @throws \Illuminate\Contracts\Container\BindingResolutionException */ public function __construct(Container $container, Repository $config, array $channelConfig) { @@ -27,13 +31,23 @@ public function __construct(Container $container, Repository $config, array $cha $this->discord = $container->make(DiscordWebHook::class, ['url' => $channelConfig['url']]); $this->recordToMessage = $this->createRecordConverter($container, $config); + + $this->ignoreExceptions = $channelConfig['ignore_exceptions'] ?? false; } - public function write(array $record): void + public function write(array|LogRecord $record): void { - foreach($this->recordToMessage->buildMessages($record) as $message) - { - $this->discord->send($message); + if ($record instanceof LogRecord) { + $record = $record->toArray(); + } + foreach($this->recordToMessage->buildMessages($record) as $message) { + try { + $this->discord->send($message); + } catch (\Exception $e) { + if (!$this->ignoreExceptions) { + throw $e; + } + } } }