Skip to content

Commit e9bc1f2

Browse files
KiNgMaRmaxbanton
authored andcommitted
Sort log entries chronologically before calling PutLogEvents. (#70)
See issues #32 and #69 for more context.
1 parent a0f1752 commit e9bc1f2

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

src/Handler/CloudWatch.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,17 @@ private function formatRecords(array $entry)
258258
*/
259259
private function send(array $entries)
260260
{
261+
// AWS expects to receive entries in chronological order...
262+
usort($entries, static function (array $a, array $b) {
263+
if ($a['timestamp'] < $b['timestamp']) {
264+
return -1;
265+
} elseif ($a['timestamp'] > $b['timestamp']) {
266+
return 1;
267+
}
268+
269+
return 0;
270+
});
271+
261272
$data = [
262273
'logGroupName' => $this->group,
263274
'logStreamName' => $this->stream,

tests/Handler/CloudWatchTest.php

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,43 @@ private function prepareMocks()
366366
->getMock();
367367
}
368368

369+
public function testSortsEntriesChronologically()
370+
{
371+
$this->prepareMocks();
372+
373+
$this
374+
->clientMock
375+
->expects($this->once())
376+
->method('PutLogEvents')
377+
->willReturnCallback(function (array $data) {
378+
$this->assertContains('record1', $data['logEvents'][0]['message']);
379+
$this->assertContains('record2', $data['logEvents'][1]['message']);
380+
$this->assertContains('record3', $data['logEvents'][2]['message']);
381+
$this->assertContains('record4', $data['logEvents'][3]['message']);
382+
383+
return $this->awsResultMock;
384+
});
385+
386+
$handler = $this->getCUT(4);
387+
388+
// created with chronological timestamps:
389+
$records = [];
390+
391+
for ($i = 1; $i <= 4; ++$i) {
392+
$record = $this->getRecord(Logger::INFO, 'record' . $i);
393+
$record['datetime'] = \DateTime::createFromFormat('U', time() + $i);
394+
$records[] = $record;
395+
}
396+
397+
// but submitted in a different order:
398+
$handler->handle($records[2]);
399+
$handler->handle($records[0]);
400+
$handler->handle($records[3]);
401+
$handler->handle($records[1]);
402+
403+
$handler->close();
404+
}
405+
369406
private function getCUT($batchSize = 1000)
370407
{
371408
return new CloudWatch($this->clientMock, $this->groupName, $this->streamName, 14, $batchSize);

0 commit comments

Comments
 (0)