Last active
August 24, 2023 16:32
-
-
Save dunkrupp/d08758349a2fe39b2bbc3b55f889cf7c to your computer and use it in GitHub Desktop.
MonoLog log file truncation method.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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