php-censor/src/Logging/BuildDBLogHandler.php

82 lines
1.7 KiB
PHP
Raw Permalink Normal View History

<?php
2016-07-19 20:28:11 +02:00
namespace PHPCensor\Logging;
2018-03-04 08:30:34 +01:00
use PHPCensor\Store\Factory;
use Monolog\Handler\AbstractProcessingHandler;
2016-07-19 20:28:11 +02:00
use PHPCensor\Model\Build;
2015-02-12 12:42:09 +01:00
use Psr\Log\LogLevel;
/**
* Class BuildDBLogHandler writes the build log to the database.
*/
class BuildDBLogHandler extends AbstractProcessingHandler
{
2013-10-26 17:25:34 +02:00
/**
* @var Build
*/
protected $build;
2013-10-26 17:25:34 +02:00
protected $logValue;
/**
* @var int last flush timestamp
*/
2018-03-05 13:32:49 +01:00
protected $flushTimestamp = 0;
/**
* @var int flush delay, seconds
*/
2018-03-05 13:32:49 +01:00
protected $flushDelay = 1;
/**
* @param Build $build
* @param bool $level
* @param bool $bubble
*/
2014-02-27 15:23:51 +01:00
public function __construct(
2013-10-26 17:25:34 +02:00
Build $build,
$level = LogLevel::INFO,
$bubble = true
) {
parent::__construct($level, $bubble);
$this->build = $build;
// We want to add to any existing saved log information.
$this->logValue = $build->getLog();
}
/**
* Destructor
*/
public function __destruct()
{
$this->flushData();
}
/**
* Flush buffered data
*/
protected function flushData()
{
$this->build->setLog($this->logValue);
Factory::getStore('Build')->save($this->build);
2018-03-05 13:32:49 +01:00
$this->flushTimestamp = time();
}
/**
* Write a log entry to the build log.
* @param array $record
*/
2013-10-26 17:25:34 +02:00
protected function write(array $record)
{
$message = (string)$record['message'];
$message = str_replace($this->build->getBuildPath(), './', $message);
$this->logValue .= $message . PHP_EOL;
2018-03-05 13:32:49 +01:00
if ($this->flushTimestamp < (time() - $this->flushDelay)) {
$this->flushData();
}
2013-10-26 17:25:34 +02:00
}
2014-02-27 15:23:51 +01:00
}