php-censor/src/Logging/BuildLogger.php

127 lines
2.9 KiB
PHP
Raw Normal View History

<?php
2016-07-19 20:28:11 +02:00
namespace PHPCensor\Logging;
2016-07-19 20:28:11 +02:00
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
*/
2014-02-27 15:23:51 +01:00
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
*/
2016-04-20 17:39:48 +02:00
public function log($message, $level = LogLevel::INFO, $context = [])
{
// Skip if no logger has been loaded.
if (!$this->logger) {
return;
}
if (!is_array($message)) {
2016-04-20 17:39:48 +02:00
$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
2016-04-20 17:39:48 +02:00
* @param \Exception $exception The exception that caused the error.
*/
public function logFailure($message, \Exception $exception = null)
{
2016-04-20 17:39:48 +02:00
$context = [];
// The psr3 log interface stipulates that exceptions should be passed
// as the exception key in the context array.
if ($exception) {
$context['exception'] = $exception;
2017-01-11 16:15:54 +01:00
$context['trace'] = $exception->getTrace();
}
2016-04-20 17:39:48 +02:00
$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");
2016-04-27 16:27:27 +02:00
}
}
/**
* Sets a logger instance on the object
*
* @param LoggerInterface $logger
*/
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
2014-02-27 15:23:51 +01:00
}