Project

General

Profile

Feature #82483 ยป FingersCrossedFileWriter.php

Artur Cichosz, 2017-09-14 10:59

 
<?php
namespace Q3i\T3Local\Core\Log\Writer;

/**
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/

use TYPO3\CMS\Core\Log\LogLevel;
use TYPO3\CMS\Core\Log\LogRecord;
use TYPO3\CMS\Core\Log\Writer\WriterInterface;

/**
* Log writer that writes the log records into a file.
* but only if during the request at least one error with severity level "error" and above ocurres
* Inspired by symfonys/monologs fingers_crossed log handler
*
* @author Artur Cichosz <a.cichosz@q3i.de>
*/
class FingersCrossedFileWriter extends \TYPO3\CMS\Core\Log\Writer\FileWriter {

private $recordBuffer = [];
private $severityThresholdHit = FALSE;

/**
* Writes the log record
* but only if during the request at leas tone error with severity level "error" and above ocurres
*
* @param LogRecord $record Log record
* @return WriterInterface $this
* @throws \RuntimeException
*/
public function writeLog(LogRecord $record) {

// force at least LogLevel::ERROR otherwise accept higher levels set with $GLOBALS["TYPO3_CONF_VARS"]['SYS']['systemLogLevel']
$logLevelThreshold = $GLOBALS["TYPO3_CONF_VARS"]['SYS']['systemLogLevel'] < LogLevel::ERROR ? LogLevel::ERROR : $GLOBALS["TYPO3_CONF_VARS"]['SYS']['systemLogLevel'];

if ($this->severityThresholdHit) {
// write the record immediately, because the severity threshold has benn hit at least once
// during this request
parent::writeLog($record);
} else if ($record->getLevel() <= $logLevelThreshold) {
// severity level threshold hit, write all stored messages until the point the error
// happend and all after
$this->severityThresholdHit = TRUE;
$this->recordBuffer[] = $record;
foreach ($this->recordBuffer as $bufRecord) {
parent::writeLog($bufRecord);
}
$this->recordBuffer = [];
} else {
// do not write immediately but store in memory
$this->recordBuffer[] = $record;
}

return $this;
}

}
    (1-1/1)