Skip to content

Commit

Permalink
Add helper method to log error without adding failure (#114)
Browse files Browse the repository at this point in the history
* #88 add helper method to log error without adding failure

* #88 code review

* #88 move LoggerTest in the right directory
  • Loading branch information
guich25 committed Feb 27, 2024
1 parent 557dd3c commit 12de1d5
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/batch/src/JobExecution.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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]);
}
}
25 changes: 25 additions & 0 deletions src/batch/tests/Job/LoggerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

declare(strict_types=1);

namespace Yokai\Batch\Tests\Job;

use Exception;
use PHPUnit\Framework\TestCase;
use Yokai\Batch\Factory\UniqidJobExecutionIdGenerator;
use Yokai\Batch\JobExecution;

class LoggerTest extends TestCase
{
public function testLogError()
{
$idGenerator = new UniqidJobExecutionIdGenerator();
$errorToLog = 'test assert logErrorMethod';
$errorException = 'test assert errorException';
$jobExecution = JobExecution::createRoot($idGenerator->generate(), 'export');
$jobExecution->logError(new Exception($errorException), $errorToLog);

self::assertStringContainsString($errorToLog, $jobExecution->getLogs()->__toString());
self::assertStringContainsString($errorException, $jobExecution->getLogs()->__toString());
}
}

0 comments on commit 12de1d5

Please sign in to comment.