Quere 100 messages before writing log to file (output handler)

This commit is contained in:
Joshua Ramon Enslin 2021-11-22 00:07:46 +01:00
parent a7d961808f
commit c7cc6c5810
Signed by: jrenslin
GPG Key ID: 46016F84501B70AE

View File

@ -11,6 +11,8 @@ declare(strict_types = 1);
*/ */
final class MDOutputHandler { final class MDOutputHandler {
const FLUSH_TO_LOGFILE_AFTER = 100;
/** @var integer */ /** @var integer */
private int $_verbosity = 0; private int $_verbosity = 0;
/** @var string */ /** @var string */
@ -26,6 +28,21 @@ final class MDOutputHandler {
/** @var boolean */ /** @var boolean */
public bool $show_operation_number = true; public bool $show_operation_number = true;
/** @var string[] */
private array $_log_queue = [];
/**
* Writes log file contents to log file.
*
* @return void
*/
public function flush_to_logfile():void {
\file_put_contents($this->_logfile, implode(PHP_EOL, $this->_log_queue), FILE_APPEND);
$this->_log_queue = [];
}
/** /**
* Function human_filesize translates byte-level filesizes to human readable ones. * Function human_filesize translates byte-level filesizes to human readable ones.
* Thanks to Jeffrey Sambells http://jeffreysambells.com/2012/10/25/human-readable-filesize-php * Thanks to Jeffrey Sambells http://jeffreysambells.com/2012/10/25/human-readable-filesize-php
@ -132,7 +149,10 @@ final class MDOutputHandler {
$message = "$statusSymbol{$contextStr}#" . sprintf("%1$07s", $this->_counter) . "" . \sprintf("%1$7s", $this->_human_filesize(\memory_get_usage())) . "{$date}{$msg}" . PHP_EOL; $message = "$statusSymbol{$contextStr}#" . sprintf("%1$07s", $this->_counter) . "" . \sprintf("%1$7s", $this->_human_filesize(\memory_get_usage())) . "{$date}{$msg}" . PHP_EOL;
if ($this->_file_logging === true) { if ($this->_file_logging === true) {
\file_put_contents($this->_logfile, $message, FILE_APPEND); $this->_log_queue[] = $message;
if (count($this->_log_queue) === self::FLUSH_TO_LOGFILE_AFTER) {
$this->flush_to_logfile();
}
} }
if (($this->_verbosity > 0 && \in_array($statusCode, [MDConsole::STATUS_UPDATE, MDConsole::STATUS_DELETION, MDConsole::STATUS_ERROR], true)) || $this->_verbosity === 2) echo $message; if (($this->_verbosity > 0 && \in_array($statusCode, [MDConsole::STATUS_UPDATE, MDConsole::STATUS_DELETION, MDConsole::STATUS_ERROR], true)) || $this->_verbosity === 2) echo $message;
@ -168,6 +188,10 @@ final class MDOutputHandler {
*/ */
public function __destruct() { public function __destruct() {
if (!empty($this->_log_queue)) {
$this->flush_to_logfile();
}
$endtime = \microtime(true); $endtime = \microtime(true);
$this->toLog("Finished operation. Processing duration: " . \strval($endtime - $this->_startTime)); $this->toLog("Finished operation. Processing duration: " . \strval($endtime - $this->_startTime));