Skip to content

Instantly share code, notes, and snippets.

@jellis
Last active November 16, 2017 03:52
Show Gist options
  • Save jellis/e5e5ebe3a7f7dd18cccd6da5afef9589 to your computer and use it in GitHub Desktop.
Save jellis/e5e5ebe3a7f7dd18cccd6da5afef9589 to your computer and use it in GitHub Desktop.
Read RDS logs
2017-10-31 00:49:13 UTC:192.168.33.1(11111):username@dbname:[13823]:LOG: duration: 0.455 ms statement: SELECT "id", "name", "email", "password", "remember_token", "created_at", "updated_at" FROM "public"."users" ORDER BY "id" ASC LIMIT 1000
2017-10-31 00:49:13 UTC:192.168.33.1(22222):username@dbname:[13823]:LOG: duration: 0.272 ms statement: SELECT COUNT(1) FROM "public"."users"
2017-11-01 02:04:21 UTC:[local]:postgres@postgres:[18956]:LOG: duration: 5.013 ms statement: SELECT COUNT(1) FROM "public"."users"
<?php
class PostgresLog implements \Iterator
{
protected $fileHandle;
protected $line;
protected $i;
protected $bytes = 0;
public function __construct($fileName) {
if (!$this->fileHandle = fopen($fileName, 'r')) {
throw new \RuntimeException('Couldn\'t open file "' . $fileName . '"');
}
}
public function rewind() {
$this->bytes = 0;
fseek($this->fileHandle, $this->bytes);
$this->line = fgets($this->fileHandle);
$this->i = 0;
}
public function valid()
{
return false !== $this->line;
}
public function current()
{
return $this->lookAhead();
}
public function key()
{
return $this->i;
}
public function next()
{
if (false !== $this->line) {
$this->bytes += mb_strlen($this->line);
$this->line = fgets($this->fileHandle);
}
}
/**
* Cannot be called multiple times in a row
* Will only reset back to the previous line after next()
* has been called
*/
public function prev()
{
if (false !== $this->line) {
fseek($this->fileHandle, $this->bytes);
$this->line = fgets($this->fileHandle);
}
}
public function __destruct()
{
fclose($this->fileHandle);
}
public function lookAhead()
{
$line = $this->line;
$this->next();
// Also need to validate the line isn't empty - if so, skip it
while (strpos($this->line, "\t") === 0) {
$line .= ' ' . trim($this->line);
$this->next();
}
$this->prev();
return $line;
}
}
<?php
$reader = new PostgresLog(logfile.txt);
foreach ($reader as $line) {
echo $line . '<br />';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment