Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion lib/Log/LogIterator.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ class LogIterator implements \Iterator {
private $handle;
private string $dateFormat;
private \DateTimeZone $timezone;
/**
* @var int[]|null
*/
private ?array $levels;

private string $buffer = '';
private string $lastLine = '';
Expand All @@ -29,11 +33,13 @@ class LogIterator implements \Iterator {
* @param resource $handle
* @param string $dateFormat
* @param string $timezone
* @param int[]|null $levels Array of log levels to include, null to include all
*/
public function __construct($handle, string $dateFormat, string $timezone) {
public function __construct($handle, string $dateFormat, string $timezone, ?array $levels = null) {
$this->handle = $handle;
$this->dateFormat = $dateFormat;
$this->timezone = new \DateTimeZone($timezone);
$this->levels = $levels;
$this->rewind();
}

Expand Down Expand Up @@ -87,11 +93,22 @@ public function next(): void {
}
$this->lastLine = substr($this->buffer, $newlinePos + 1);
$this->buffer = substr($this->buffer, 0, $newlinePos);

// Skip lines that don't match the log level
if ($this->levels !== null && !$this->matchesLevelFilter($this->lastLine)) {
continue;
}

$this->currentKey++;
return;
} elseif ($this->position === 0) {
$this->lastLine = $this->buffer;
$this->buffer = '';

if ($this->levels !== null && !$this->matchesLevelFilter($this->lastLine)) {
return;
}

$this->currentKey++;
return;
} else {
Expand All @@ -100,6 +117,24 @@ public function next(): void {
}
}

/**
* Check if a log line matches the allowed levels.
* Inaccurate check before full JSON decoding,
* CallbackFilterIterator still required to validate the entry.
*/
private function matchesLevelFilter(string $line): bool {
$levelPos = strpos($line, '"level":');
if ($levelPos === false) {
return false;
}
$digit = substr($line, $levelPos + 8, 1);
if (!ctype_digit($digit)) {
return false;
}
$level = (int)$digit;
return in_array($level, $this->levels, true);
}

public function valid(): bool {
if (!is_resource($this->handle)) {
return false;
Expand Down
2 changes: 1 addition & 1 deletion lib/Log/LogIteratorFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public function getLogIterator(array $levels): \Iterator {
if ($log instanceof IFileBased) {
$handle = fopen($log->getLogFilePath(), 'rb');
if ($handle) {
$iterator = new LogIterator($handle, $dateFormat, $timezone);
$iterator = new LogIterator($handle, $dateFormat, $timezone, $levels);
return new \CallbackFilterIterator($iterator, function ($logItem) use ($levels) {
return $logItem && in_array($logItem['level'], $levels);
});
Expand Down
Loading