diff --git a/src/Monolog/Handler/StreamHandler.php b/src/Monolog/Handler/StreamHandler.php index f3e11c8c5..cc9202cca 100644 --- a/src/Monolog/Handler/StreamHandler.php +++ b/src/Monolog/Handler/StreamHandler.php @@ -155,6 +155,36 @@ protected function write(LogRecord $record): void } } + /** + * {@inheritDoc} + */ + public function handle(LogRecord $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 882f8d843..8549e2e77 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,17 +55,31 @@ public function testCloseKeepsExternalHandlersOpen() /** * @covers Monolog\Handler\StreamHandler::close */ - public function testClose() + public function testHandlerOwnedHandlesAreClosedAfterEachWrite() { - $handler = new StreamHandler('php://memory'); - $handler->handle($this->getRecord(Level::Warning, 'test')); + $handler = new StreamHandler(__DIR__.'/test.log'); + $handler->handle($this->getRecord()); $stream = $handler->getStream(); - $this->assertTrue(is_resource($stream)); - $handler->close(); $this->assertFalse(is_resource($stream)); } + /** + * @covers Monolog\Handler\StreamHandler::close + */ + public function testHandlerOwnedHandlesAreClosedAfterEachBatchWrite() + { + $handler = self::getMockBuilder(StreamHandler::class) + ->onlyMethods(['close']) + ->setConstructorArgs([__DIR__.'/test.log']) + ->getMock(); + $handler->expects($this->once()) + ->method('close'); + $handler->handleBatch([$this->getRecord(), $this->getRecord(), $this->getRecord()]); + + self::assertCount(3, file(__DIR__.'/test.log')); + } + /** * @covers Monolog\Handler\StreamHandler::close * @covers Monolog\Handler\Handler::__sleep