Skip to content

Commit ccc9a29

Browse files
authored
Log to custom callback (#6)
1 parent 877a433 commit ccc9a29

File tree

3 files changed

+39
-1
lines changed

3 files changed

+39
-1
lines changed

.gitattributes

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,6 @@
33
.gitattributes export-ignore
44
.gitignore export-ignore
55
.php_cs export-ignore
6+
Makefile export-ignore
67
phpstan.neon export-ignore
78
phpunit.xml export-ignore

lib/ErrorHandler.php

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,11 @@ final class ErrorHandler
5555
*/
5656
private $emailCallback;
5757

58+
/**
59+
* @var callable
60+
*/
61+
private $errorLogCallback = '\\error_log';
62+
5863
/**
5964
* @var array<int, bool>
6065
*/
@@ -99,6 +104,16 @@ public function __construct(callable $emailCallback)
99104
$this->emailCallback = $emailCallback;
100105
}
101106

107+
public function setErrorLogCallback(callable $callback): void
108+
{
109+
$this->errorLogCallback = $callback;
110+
}
111+
112+
public function getErrorLogCallback(): callable
113+
{
114+
return $this->errorLogCallback;
115+
}
116+
102117
public function setAutoExit(bool $autoExit): void
103118
{
104119
$this->autoExit = $autoExit;
@@ -365,6 +380,8 @@ public function logException(Throwable $exception): void
365380
return;
366381
}
367382

383+
$errorLogCallback = $this->errorLogCallback;
384+
368385
$i = 0;
369386
do {
370387
$output = \sprintf('%s%s: %s in %s:%s%s%s',
@@ -377,7 +394,7 @@ public function logException(Throwable $exception): void
377394
$this->purgeTrace($exception->getTraceAsString())
378395
);
379396

380-
\error_log($output);
397+
$errorLogCallback($output);
381398

382399
++$i;
383400
} while ($exception = $exception->getPrevious());

tests/ErrorHandlerTest.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,4 +306,24 @@ public function test404SpecificExceptionForHeaders(): void
306306

307307
self::assertStringContainsString('404: Not Found', $this->errorHandler->renderHtmlException(new RuntimeException()));
308308
}
309+
310+
public function testCanSetCustomErrorLogCallback(): void
311+
{
312+
$this->errorHandler->setLogErrors(true);
313+
self::assertSame('\\error_log', $this->errorHandler->getErrorLogCallback());
314+
315+
$data = [];
316+
$customCallback = static function (string $text) use (& $data): void {
317+
$data[] = $text;
318+
};
319+
320+
$this->errorHandler->setErrorLogCallback($customCallback);
321+
322+
self::assertSame($customCallback, $this->errorHandler->getErrorLogCallback());
323+
324+
$this->errorHandler->logException($this->exception);
325+
326+
self::assertSame(0, \filesize($this->errorLog));
327+
self::assertStringContainsString($this->exception->getMessage(), \var_export($data, true));
328+
}
309329
}

0 commit comments

Comments
 (0)