Skip to content

Instantly share code, notes, and snippets.

@dunkrupp
Last active August 24, 2023 16:32
Show Gist options
  • Save dunkrupp/d08758349a2fe39b2bbc3b55f889cf7c to your computer and use it in GitHub Desktop.
Save dunkrupp/d08758349a2fe39b2bbc3b55f889cf7c to your computer and use it in GitHub Desktop.
MonoLog log file truncation method.
<?php
namespace \App\Logger;
class Logger extends \Monolog\Logger
{
const MAX_SIZE = 2097152;
/**
* Truncates the log file per iteration.
*/
public function truncate()
{
/** @var \App\Logger\Handler $handlers */
$handlers = $this->getHandlers()['system'];
$path = $handlers->getUrl();
try {
$file = new \SplFileObject($path, 'c');
if ($file->getSize() >= self::MAX_SIZE) {
$file->ftruncate(0);
$file->rewind();
echo 'Truncated ' . $file->getBasename() . PHP_EOL;
$file = null;
}
} catch (\Exception $e) {
// Silence
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment