Skip to content

Commit

Permalink
Log to custom callback (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
Slamdunk authored Sep 30, 2020
1 parent 877a433 commit ccc9a29
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -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
19 changes: 18 additions & 1 deletion lib/ErrorHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ final class ErrorHandler
*/
private $emailCallback;

/**
* @var callable
*/
private $errorLogCallback = '\\error_log';

/**
* @var array<int, bool>
*/
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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',
Expand All @@ -377,7 +394,7 @@ public function logException(Throwable $exception): void
$this->purgeTrace($exception->getTraceAsString())
);

\error_log($output);
$errorLogCallback($output);

++$i;
} while ($exception = $exception->getPrevious());
Expand Down
20 changes: 20 additions & 0 deletions tests/ErrorHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}

0 comments on commit ccc9a29

Please sign in to comment.