Skip to content

Commit

Permalink
Sort log entries chronologically before calling PutLogEvents. (#70)
Browse files Browse the repository at this point in the history
See issues #32 and #69 for more context.
  • Loading branch information
KiNgMaR authored and maxbanton committed Oct 6, 2019
1 parent a0f1752 commit e9bc1f2
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Handler/CloudWatch.php
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,17 @@ private function formatRecords(array $entry)
*/
private function send(array $entries)
{
// AWS expects to receive entries in chronological order...
usort($entries, static function (array $a, array $b) {
if ($a['timestamp'] < $b['timestamp']) {
return -1;
} elseif ($a['timestamp'] > $b['timestamp']) {
return 1;
}

return 0;
});

$data = [
'logGroupName' => $this->group,
'logStreamName' => $this->stream,
Expand Down
37 changes: 37 additions & 0 deletions tests/Handler/CloudWatchTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,43 @@ private function prepareMocks()
->getMock();
}

public function testSortsEntriesChronologically()
{
$this->prepareMocks();

$this
->clientMock
->expects($this->once())
->method('PutLogEvents')
->willReturnCallback(function (array $data) {
$this->assertContains('record1', $data['logEvents'][0]['message']);
$this->assertContains('record2', $data['logEvents'][1]['message']);
$this->assertContains('record3', $data['logEvents'][2]['message']);
$this->assertContains('record4', $data['logEvents'][3]['message']);

return $this->awsResultMock;
});

$handler = $this->getCUT(4);

// created with chronological timestamps:
$records = [];

for ($i = 1; $i <= 4; ++$i) {
$record = $this->getRecord(Logger::INFO, 'record' . $i);
$record['datetime'] = \DateTime::createFromFormat('U', time() + $i);
$records[] = $record;
}

// but submitted in a different order:
$handler->handle($records[2]);
$handler->handle($records[0]);
$handler->handle($records[3]);
$handler->handle($records[1]);

$handler->close();
}

private function getCUT($batchSize = 1000)
{
return new CloudWatch($this->clientMock, $this->groupName, $this->streamName, 14, $batchSize);
Expand Down

0 comments on commit e9bc1f2

Please sign in to comment.