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 884aa47 commit e1b5255
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 4 deletions.
30 changes: 30 additions & 0 deletions src/Monolog/Handler/StreamHandler.php
Expand Up @@ -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
Expand Down
25 changes: 21 additions & 4 deletions tests/Monolog/Handler/StreamHandlerTest.php
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,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));
}

Expand Down

0 comments on commit e1b5255

Please sign in to comment.