From 12de1d536fbef6178868ea22a0cce12478f4e8e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20GUICHERD?= <47358201+guich25@users.noreply.github.com> Date: Tue, 27 Feb 2024 15:34:43 +0100 Subject: [PATCH] Add helper method to log error without adding failure (#114) * #88 add helper method to log error without adding failure * #88 code review * #88 move LoggerTest in the right directory --- src/batch/src/JobExecution.php | 12 ++++++++++++ src/batch/tests/Job/LoggerTest.php | 25 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 src/batch/tests/Job/LoggerTest.php diff --git a/src/batch/src/JobExecution.php b/src/batch/src/JobExecution.php index 5160d107..d56aa322 100644 --- a/src/batch/src/JobExecution.php +++ b/src/batch/src/JobExecution.php @@ -8,6 +8,7 @@ use DateTime; use DateTimeInterface; use Psr\Log\LoggerInterface; +use Psr\Log\LogLevel; use Throwable; use Yokai\Batch\Exception\ImmutablePropertyException; use Yokai\Batch\Factory\JobExecutionIdGeneratorInterface; @@ -379,4 +380,15 @@ public function getLogger(): LoggerInterface { return $this->logger; } + + /** + * Log the error from a Throwable + * @param Throwable $error The error to log + * @param string|null $message The message to use while logging + * @param LogLevel::* $level The level to use while logging + */ + public function logError(Throwable $error, string $message = null, string $level = LogLevel::ERROR): void + { + $this->logger->log($level, $message ?? 'An error occurred', ['error' => (string)$error]); + } } diff --git a/src/batch/tests/Job/LoggerTest.php b/src/batch/tests/Job/LoggerTest.php new file mode 100644 index 00000000..e1708b18 --- /dev/null +++ b/src/batch/tests/Job/LoggerTest.php @@ -0,0 +1,25 @@ +generate(), 'export'); + $jobExecution->logError(new Exception($errorException), $errorToLog); + + self::assertStringContainsString($errorToLog, $jobExecution->getLogs()->__toString()); + self::assertStringContainsString($errorException, $jobExecution->getLogs()->__toString()); + } +}