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()); + } +}