Skip to content

Commit

Permalink
Move GC trigger back to isDuplicate()
Browse files Browse the repository at this point in the history
  • Loading branch information
cracksalad committed Apr 12, 2024
1 parent d2b2a67 commit 17e3917
Showing 1 changed file with 12 additions and 11 deletions.
23 changes: 12 additions & 11 deletions src/Monolog/Handler/DeduplicationHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ class DeduplicationHandler extends BufferHandler
protected Level $deduplicationLevel;

protected int $time;

protected bool $gc = false;

/**
* @param HandlerInterface $handler Handler.
Expand Down Expand Up @@ -73,15 +75,6 @@ public function flush(): void

if (file_exists($this->deduplicationStore)) {
$store = file($this->deduplicationStore, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if (is_array($store)) {
$yesterday = time() - 86400;
for ($i = 0; $i < count($store); $i++) {
if (substr($store[$i], 0, 10) < $yesterday) {
$gc = true;
break;
}
}
}
}

$passthru = null;
Expand All @@ -106,25 +99,31 @@ public function flush(): void

$this->clear();

if ($gc) {
if ($this->gc) {
$this->collectLogs();
}
}

/**
* If there is a store entry older than e.g. a day, this method should set `$this->gc` to `true` to trigger garbage collection.
* @param string[] $store The deduplication store
*/
protected function isDuplicate(array $store, LogRecord $record): bool
{
$timestampValidity = $record->datetime->getTimestamp() - $this->time;
$expectedMessage = preg_replace('{[\r\n].*}', '', $record->message);
$yesterday = time() - 86400;

for ($i = count($store) - 1; $i >= 0; $i--) {
list($timestamp, $level, $message) = explode(':', $store[$i], 3);

if ($level === $record->level->getName() && $message === $expectedMessage && $timestamp > $timestampValidity) {
return true;
}
}

if ($timestamp < $yesterday) {
$this->gc = true;
}
}

return false;
Expand Down Expand Up @@ -170,5 +169,7 @@ private function collectLogs(): void

flock($handle, LOCK_UN);
fclose($handle);

$this->gc = false;
}
}

0 comments on commit 17e3917

Please sign in to comment.