Skip to content

Commit

Permalink
Close file handle after each write, refs #1862, refs #1860, refs #1634
Browse files Browse the repository at this point in the history
  • Loading branch information
Seldaek committed Apr 15, 2024
1 parent a4471eb commit d6143bc
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 5 deletions.
30 changes: 30 additions & 0 deletions src/Monolog/Handler/StreamHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 26 additions & 5 deletions tests/Monolog/Handler/StreamHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit d6143bc

Please sign in to comment.