diff --git a/.gitattributes b/.gitattributes index b5f5cda..5b41632 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,5 +3,6 @@ .gitattributes export-ignore .gitignore export-ignore .php_cs export-ignore +Makefile export-ignore phpstan.neon export-ignore phpunit.xml export-ignore diff --git a/lib/ErrorHandler.php b/lib/ErrorHandler.php index ee9c880..8b5d8fa 100644 --- a/lib/ErrorHandler.php +++ b/lib/ErrorHandler.php @@ -55,6 +55,11 @@ final class ErrorHandler */ private $emailCallback; + /** + * @var callable + */ + private $errorLogCallback = '\\error_log'; + /** * @var array */ @@ -99,6 +104,16 @@ public function __construct(callable $emailCallback) $this->emailCallback = $emailCallback; } + public function setErrorLogCallback(callable $callback): void + { + $this->errorLogCallback = $callback; + } + + public function getErrorLogCallback(): callable + { + return $this->errorLogCallback; + } + public function setAutoExit(bool $autoExit): void { $this->autoExit = $autoExit; @@ -365,6 +380,8 @@ public function logException(Throwable $exception): void return; } + $errorLogCallback = $this->errorLogCallback; + $i = 0; do { $output = \sprintf('%s%s: %s in %s:%s%s%s', @@ -377,7 +394,7 @@ public function logException(Throwable $exception): void $this->purgeTrace($exception->getTraceAsString()) ); - \error_log($output); + $errorLogCallback($output); ++$i; } while ($exception = $exception->getPrevious()); diff --git a/tests/ErrorHandlerTest.php b/tests/ErrorHandlerTest.php index 0bad68b..4ea2926 100644 --- a/tests/ErrorHandlerTest.php +++ b/tests/ErrorHandlerTest.php @@ -306,4 +306,24 @@ public function test404SpecificExceptionForHeaders(): void self::assertStringContainsString('404: Not Found', $this->errorHandler->renderHtmlException(new RuntimeException())); } + + public function testCanSetCustomErrorLogCallback(): void + { + $this->errorHandler->setLogErrors(true); + self::assertSame('\\error_log', $this->errorHandler->getErrorLogCallback()); + + $data = []; + $customCallback = static function (string $text) use (& $data): void { + $data[] = $text; + }; + + $this->errorHandler->setErrorLogCallback($customCallback); + + self::assertSame($customCallback, $this->errorHandler->getErrorLogCallback()); + + $this->errorHandler->logException($this->exception); + + self::assertSame(0, \filesize($this->errorLog)); + self::assertStringContainsString($this->exception->getMessage(), \var_export($data, true)); + } }