php-censor/src/Logging/BuildLogger.php
Dmitry Khomutov 069026bc2d
Added ability to merge in-database project config over in-repository
config instead of only overwrite. This commit solve issues: #14, #70,
#106, #121.
2018-04-15 15:58:23 +07:00

127 lines
2.9 KiB
PHP

<?php
namespace PHPCensor\Logging;
use PHPCensor\Model\Build;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
/**
* Class BuildLogger
*/
class BuildLogger implements LoggerAwareInterface
{
/**
* @var LoggerInterface
*/
protected $logger;
/**
* @var Build
*/
protected $build;
/**
* @param LoggerInterface $logger
* @param Build $build
*/
public function __construct(LoggerInterface $logger, Build $build)
{
$this->logger = $logger;
$this->build = $build;
}
/**
* Add an entry to the build log.
*
* @param string|string[] $message
* @param string $level
* @param mixed[] $context
*/
public function log($message, $level = LogLevel::INFO, $context = [])
{
// Skip if no logger has been loaded.
if (!$this->logger) {
return;
}
if (!is_array($message)) {
$message = [$message];
}
// The build is added to the context so the logger can use
// details from it if required.
$context['build'] = $this->build;
foreach ($message as $item) {
$this->logger->log($level, $item, $context);
}
}
/**
* Add a warning-coloured message to the log.
*
* @param string $message
*/
public function logWarning($message)
{
$this->log("\033[0;31m" . $message . "\033[0m", LogLevel::WARNING);
}
/**
* Add a success-coloured message to the log.
*
* @param string $message
*/
public function logSuccess($message)
{
$this->log("\033[0;32m" . $message . "\033[0m");
}
/**
* Add a failure-coloured message to the log.
*
* @param string $message
* @param \Exception $exception The exception that caused the error.
*/
public function logFailure($message, \Exception $exception = null)
{
$context = [];
// The psr3 log interface stipulates that exceptions should be passed
// as the exception key in the context array.
if ($exception) {
$context['exception'] = $exception;
$context['trace'] = $exception->getTrace();
}
$this->log("\033[0;31m" . $message . "\033[0m", LogLevel::ERROR, $context);
}
/**
* Add a debug-coloured message to the log.
*
* @param string $message
*/
public function logDebug($message)
{
if (
(defined('DEBUG_MODE') && DEBUG_MODE) ||
((boolean)$this->build->getExtra('debug'))
) {
$this->log("\033[0;36m" . $message . "\033[0m");
}
}
/**
* Sets a logger instance on the object
*
* @param LoggerInterface $logger
*/
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
}