diff --git a/src/Monolog/Handler/StreamHandler.php b/src/Monolog/Handler/StreamHandler.php index 561d9c755..8f1f7fe31 100644 --- a/src/Monolog/Handler/StreamHandler.php +++ b/src/Monolog/Handler/StreamHandler.php @@ -171,6 +171,36 @@ protected function write(array $record): void } } + /** + * {@inheritDoc} + */ + public function handle(array $record): bool + { + $result = parent::handle($record); + + // close the resource if possible to reopen it after we are done writing + if ($this->url !== null && $this->url !== 'php://memory') { + $this->close(); + } + + return $result; + } + + /** + * {@inheritDoc} + */ + public function handleBatch(array $records): void + { + foreach ($records as $record) { + parent::handle($record); + } + + // close the resource if possible to reopen it after we are done writing + if ($this->url !== null && $this->url !== 'php://memory') { + $this->close(); + } + } + /** * Write to stream * @param resource $stream diff --git a/tests/Monolog/Handler/StreamHandlerTest.php b/tests/Monolog/Handler/StreamHandlerTest.php index 8c69cc58e..86af3be80 100644 --- a/tests/Monolog/Handler/StreamHandlerTest.php +++ b/tests/Monolog/Handler/StreamHandlerTest.php @@ -17,6 +17,13 @@ class StreamHandlerTest extends TestCase { + public function tearDown(): void + { + parent::tearDown(); + + @unlink(__DIR__.'/test.log'); + } + /** * @covers Monolog\Handler\StreamHandler::__construct * @covers Monolog\Handler\StreamHandler::write @@ -48,14 +55,24 @@ public function testCloseKeepsExternalHandlersOpen() /** * @covers Monolog\Handler\StreamHandler::close */ - public function testClose() + public function testHandlerOwnedHandlesAreClosedAfterEachWrite() { - $handler = new StreamHandler('php://memory'); + $handler = new StreamHandler(__DIR__.'/test.log'); $handler->handle($this->getRecord(Logger::WARNING, 'test')); $stream = $handler->getStream(); - $this->assertTrue(is_resource($stream)); - $handler->close(); + $this->assertFalse(is_resource($stream)); + } + + /** + * @covers Monolog\Handler\StreamHandler::close + */ + public function testHandlerOwnedHandlesAreClosedAfterEachBatchWrite() + { + $handler = new StreamHandler(__DIR__.'/test.log'); + $handler->handleBatch([$this->getRecord(Logger::WARNING, 'test')]); + $stream = $handler->getStream(); + $this->assertFalse(is_resource($stream)); }